简体   繁体   中英

How to get Count from Subquery when main query returns no records

The MYSQL query below gives me the output I need when there are records found in the main query eg

RETURN:

username  |  total_favs
this_user |  4

But I get nothing return if no records found in main query. I want to get something like this:

RETURN:

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

Switch it around so favourites is the main query:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM