我使用LEFT JOIN组合了三个表-- persons、properties、totals。我发现下面的查询非常快,但是它没有给出table-1中的所有行,这些行在table-2或table-3中没有对应的数据。基本上,它只给我在table-2和table-3中有数据的行。
SELECT a.*, b.propery_address, c.person_asset_total
FROM persons AS a
LEFT JOIN properties AS b ON a.id = b.person_id
LEFT JOIN totals AS c ON a.id = c.person_id
WHERE a.city = 'New York' AND
c.description = 'Total Immovable'然而,下面的查询通过包括table-1中的所有行给出了正确的结果,而不管table-2和table-3中是否有相应的数据。但是,这个查询需要很长的处理时间。
FROM persons AS a
LEFT JOIN
properties AS b ON a.id = b.person_id
LEFT JOIN
(SELECT person_id, person_asset_total
FROM totals
WHERE description = 'Total Immovable'
) AS c ON a.id = c.person_id
WHERE a.city = 'New York'有没有更好的方法来编写一个查询,它将提供与第二个查询相同的数据,但执行速度与第一个查询相同?
发布于 2017-01-30 23:49:13
不要使用子查询:
SELECT p.*, pr.propery_address, t.person_asset_total
FROM persons p LEFT JOIN
properties pr
ON p.id = pr.person_id LEFT JOIN
totals t
ON a.id = c.person_id AND t.description = 'Total Immovable'
WHERE p.city = 'New York';您的方法在几乎任何其他数据库中都适用。然而,MySQL实现了“派生表”,这使得它们更难优化。上述方法具有相同的效果。
您还会注意到,我将表别名更改为表名的缩写。这使得查询更容易理解。
https://stackoverflow.com/questions/41939986
复制相似问题