mysql查询在group by中包括零计数

时间:2014-07-15 20:35:24

标签: mysql

我看过这些例子但仍需要指导。我的查询有效,但不包括结果中的零计数 - 对mysqli或pdo不感兴趣,只是坚持查询并需要一个可靠的才能拉出我的头发。如何调整以下值,以便在计数中包含零?

SELECT users.user_id,
       users.contact_person,
       users.company,
       users.country,
       users.pic_small,
       users.website,
       COUNT(*)
FROM trading
JOIN users ON users.user_id = trading.user_id
WHERE users.trader_or_bond = %s
GROUP BY user_id
ORDER BY count(trading.user_id) DESC

3 个答案:

答案 0 :(得分:0)

也许是这样的?添加ifnull部分..必须返回null但是为了返回零,您可能需要将连接更改为LEFT连接并将条件添加到连接

SELECT u.user_id,
       u.contact_person,
       u.company,
       u.country,
       u.pic_small,
       u.website,
       IFNULL(COUNT(*), 0) as counter
FROM trading t
LEFT JOIN users u
    ON u.user_id = t.user_id
   AND u.trader_or_bond = %s
GROUP BY u.user_id
ORDER BY COUNT(u.user_id) DESC

答案 1 :(得分:0)

也许您只想将where子句移动到条件聚合:

SELECT u.user_id, u.contact_person, u.company, u.country, u.pic_small, u.website,
       SUM(u.trader_or_bond = %s)
FROM trading t JOIN
     users u
     ON u.user_id = t.user_id
GROUP BY u.user_id
ORDER BY count(t.user_id) DESC;

编辑:

对于修订后的要求,请使用left outer join

SELECT u.user_id, u.contact_person, u.company, u.country, u.pic_small, u.website,
       SUM(u.trader_or_bond = %s and t.user_id is not null)
FROM users u LEFT JOIN
     trading t 
     ON u.user_id = t.user_id
GROUP BY u.user_id
ORDER BY count(t.user_id) DESC;

答案 2 :(得分:0)

移动你在on子句中的部分,并将连接更改为左连接,以便从trading表计数将其计算为0

SELECT 
  users.user_id,
  users.contact_person,
  users.company,
  users.country,
  users.pic_small,
  users.website,
  COUNT(trading.user_id) 
FROM
  trading 
  LEFT JOIN users 
    ON users.user_id = trading.user_id 
AND  users.trader_or_bond = % s 
GROUP BY user_id 
ORDER BY COUNT(trading.user_id) DESC