1

当在主查询中找到记录时,下面的 MYSQL 查询为我提供了我需要的输出,例如

返回:

username  |  total_favs
this_user |  4

但是如果在主查询中没有找到任何记录,我什么也得不到。我想得到这样的东西:

返回:

username  |  total_favs
null |  4

SELECT 
  c.username,
  (SELECT COUNT(*) AS total_records FROM favourites f WHERE f.pic_id = 177) AS `total_favs`
FROM
  comments c
WHERE
  c.pic_id = 177
4

1 回答 1

3

切换它favourites是主要查询:

SELECT c.username, COUNT(*) AS total_favs
FROM favourites f
LEFT OUTER JOIN comments c on f.pic_id = c.pic_id
WHERE f.pic_id = 177
GROUP BY c.username
于 2012-08-29T16:29:07.770 回答