【问题标题】:What is the difference between these two queries (condition position)?这两个查询(条件位置)有什么区别?
【发布时间】:2014-07-04 01:20:45
【问题描述】:

第一个查询:

SELECT SUM(Rent.paid) AS Rent__summed_rents 
FROM rents AS Rent 
LEFT JOIN contracts ON contracts.id = Rent.id 
LEFT JOIN units ON contracts.unit_id = units.id AND units.owner_id = 29

第二次查询:

SELECT SUM(Rent.paid) AS Rent__summed_rents 
FROM rents AS Rent 
LEFT JOIN contracts ON contracts.id = Rent.id 
LEFT JOIN units ON contracts.unit_id = units.id
WHERE units.owner_id = 29

我应该指出结果不一样!

【问题讨论】:

    标签: mysql join where-clause


    【解决方案1】:

    区别在于过滤条件。

    例如,在您的第一个查询中,它将选择sum(rent.paid),无论其中任何一个连接是否实际产生记录。这样做的好处是,如果您需要数据而不管连接是否有效,但确实想要过滤连接,那么您可以将条件过滤器放在连接子句本身上。

    在您的第二个查询中,条件过滤器位于 where,如果连接有效(即使它们是左连接),会生成您的 sum(rent.paid)

    【讨论】:

    • 谢谢。如果我理解正确:第一个条件是过滤 join 而不是 sum?
    猜你喜欢
    • 1970-01-01
    • 2010-12-19
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多