我正在尝试使用某些条件创建LEFT JOIN查询,但它似乎行为奇怪。任何ON子句条件都没有对它起作用:
SELECT c.country_id, c.country_name, IFNULL(MAX(b.bid_amount),0)
FROM countries AS c
LEFT JOIN items_bids AS b
ON c.country_id = b.bid_country_id
AND b.bid_removed = 0
LEFT JOIN advertisers AS a
ON a.advertiser_id = b.bid_advertiser_id
AND a.advertiser_balance > 0
AND a.advertiser_review = 0
LEFT JOIN items AS n
ON b.bid_item_id = n.item_id
AND n.item_approved = 1
AND n.item_deleted = 0
AND n.item_paused = 0
GROUP BY c.country_name
它的结果与此相同:
SELECT c.country_id, c.country_name, IFNULL(MAX(b.bid_amount),0)
FROM countries AS c
LEFT JOIN items_bids AS b
ON c.country_id = b.bid_country_id
LEFT JOIN advertisers AS a
ON a.advertiser_id = b.bid_advertiser_id
LEFT JOIN items AS n
ON b.bid_item_id = n.item_id
GROUP BY c.country_name
我确定它应该是一个不同的结果,因为如果我将这些条件放在WHERE子句而不是ON子句中它确实有效。
问题是,我正在使用LEFT JOIN,因为我不想从结果中消除任何国家。
答案 0 :(得分:0)
您的on
- 条件无法按预期工作,因为您使用left join
来连接表格,然后从不使用它们,因此它们无效。您只能使用max(b.bid_amount)
和countries
,因此只有b
和countries
上的条件才会生效。
例如,如果advertisers
的某些行符合您的on
条件,那么它们会被加入,但对b.bid_amount
没有影响,因为您不会使用它们(它们)会对例如count(*)
或sum(b.bid_amount)
产生影响。如果advertisers
没有行,则由于b.bid_amount
,它们对left join
也没有影响。所以你的条件并不重要。
您的第一个代码相当于
SELECT c.country_id, c.country_name, IFNULL(MAX(b.bid_amount),0)
FROM countries AS c
LEFT JOIN items_bids AS b
ON c.country_id = b.bid_country_id
AND b.bid_removed = 0
GROUP BY c.country_name
,您的第二个代码相当于
SELECT c.country_id, c.country_name, IFNULL(MAX(b.bid_amount),0)
FROM countries AS c
LEFT JOIN items_bids AS b
ON c.country_id = b.bid_country_id
GROUP BY c.country_name
并且他们给出相同的结果也许并不奇怪(取决于
您的数据和行数b.bid_removed = 0
。试试b.bid_removed = 1
您可能会看到效果,这是唯一相关的条件。)
如果你提出了条件,例如在AND a.advertiser_balance > 0
- 子句中where
,mysql只会选择a.advertiser_balance
不为空的行!因此,left join
将充当join
,并且这可能会产生不同的结果并不令人惊讶。
由于你没有描述你真正想要达到的目标,我会猜测并删除一些左连接。您将获得所有国家/地区,并且所有on
条件都可以使用。
尝试
SELECT c.country_id, c.country_name, IFNULL(MAX(b.bid_amount),0)
FROM countries AS c
LEFT JOIN items_bids AS b
ON c.country_id = b.bid_country_id
AND b.bid_removed = 0
JOIN advertisers AS a
ON a.advertiser_id = b.bid_advertiser_id
AND a.advertiser_balance > 0
AND a.advertiser_review = 0
JOIN items AS n
ON b.bid_item_id = n.item_id
AND n.item_approved = 1
AND n.item_deleted = 0
AND n.item_paused = 0
GROUP BY c.country_name