[英]MAX() doesn't return NULL rows from LEFT JOIN
This will return multiple rows: 这将返回多行:
SELECT w.word_id, w.word_word, w.word_visits, w.word_created_unix, b.bid_per_visit
FROM keywords_words AS w
LEFT JOIN keywords_bids AS b
ON w.word_id = b.bid_word_id WHERE w.word_word LIKE 'an%'
ORDER BY w.word_visits DESC
LIMIT 10
But this will only return rows where there is a bid in keywords_bids: 但这只会返回在keyword_bids中有出价的行:
SELECT w.word_id, w.word_word, w.word_visits, w.word_created_unix, MAX(b.bid_per_visit)
FROM keywords_words AS w
LEFT JOIN keywords_bids AS b
ON w.word_id = b.bid_word_id WHERE w.word_word LIKE 'an%'
ORDER BY w.word_visits DESC
LIMIT 10
How do I get it to return the MAX(b.bid_per_visit)
if there is a bid, and zero if there isn't any bids. 如果有出价,如何获取它以返回MAX(b.bid_per_visit)
如果没有出价,则如何返回零。
Not excluding rows from the original LIKE search basically. 基本上不从原始LIKE搜索中排除行。
Use coalesce: 使用合并:
...
MAX(coalesce(b.bid_per_visit, 0))
...
Or don't group by and simply: 或者不要简单地分组:
...
coalesce(b.bid_per_visit, 0)
...
coalesce()
returns the first non-null value in its list of values. coalesce()
返回其值列表中的第一个非空值。 With left joins, nulls are returned for the joiner table is there's no matching row. 对于左联接,如果没有匹配的行,则为联接器表返回null。
IFNULL(MAX(b.bid_per_visit),0)的使用解决了您的问题,如果MAX(b.bid_per_visit)为null,则返回0,如果b.bid_per_visit不为null,则返回最大值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.