在内连接中,select count返回null而不是0

时间:2016-01-03 10:06:20

标签: mysql

我正在使用以下查询来获取表users中的用户名列表,该列表尚未向具有ID&x; xXXXxXXxxx&x的用户发送请求或收到请求#39;在表friends中:

SELECT u.user, f1.c1, f2.c2
FROM users u
LEFT JOIN
(
    SELECT uid, fid, COUNT(*) AS c1
    FROM friends f
    WHERE f.fid = 'xXXXxXXxxx'
) AS f1
ON f1.uid = u.uid
LEFT JOIN
(
    SELECT uid, fid, count(*) AS c2
    FROM friends f
    WHERE f.uid = 'xXXXxXXxxx'
) AS f2
ON f2.fid = u.uid;

输出:

+------------+------+------+
| user       | c1   | c2   |
+------------+------+------+
| User1      | NULL | NULL |
| User2      | NULL | 1    |
| User3      | NULL | NULL |
| User4      | 1    | NULL |
| User5      | NULL | NULL |
+------------+------+------+

为什么我为计数而不是0获取NULL值?并且有更好的方法来运行此查询吗?

3 个答案:

答案 0 :(得分:1)

如果你的结果是正确的,除了0,那么你可以使用IFNULL()函数来获取0 IFNULL(f1.c1,0);

SELECT u.user,IFNULL(f1.c1,0), IFNULL(f2.c2,0)
FROM users u
LEFT JOIN
(
    SELECT uid, fid, COUNT(*) AS c1
    FROM friends f
    WHERE f.fid = 'xXXXxXXxxx'
 ) AS f1
ON f1.uid = u.uid
LEFT JOIN
(
    SELECT uid, fid, count(*) AS c2
    FROM friends f
    WHERE f.uid = 'xXXXxXXxxx'
) AS f2
ON f2.fid = u.uid;

还可以使用GROUP BY按用户获取一行用户数

  

LEFT JOIN:LEFT JOIN关键字返回左表中的所有行   (table1),右表(table2)中的匹配行。该   当没有匹配时,右侧的结果为NULL。

enter image description here

http://dev.mysql.com/doc/refman/5.7/en/left-join-optimization.html http://www.w3schools.com/sql/sql_join_left.asp

现在如果您想要获得0,那么您应该使用IFNULL()功能

答案 1 :(得分:1)

或者只是做

SELECT user, 
       (SELECT COUNT(*) FROM friends f WHERE f.uid=u.uid AND f.fid = 'xXXXxXXxxx') f1,
       (SELECT COUNT(*) FROM friends f WHERE f.fid=u.uid AND f.uid = 'xXXXxXXxxx') f2
FROM users u

修改,以符合下面的评论

SELECT * FROM 
       ( SELECT user, 
         (SELECT COUNT(*) FROM friends f WHERE f.uid=u.uid AND f.fid = 'xXXXxXXxxx') f1,
         (SELECT COUNT(*) FROM friends f WHERE f.fid=u.uid AND f.uid = 'xXXXxXXxxx') f2
         FROM users u
       ) uu 
WHERE f1 = 0 AND f2 = 0

或者,更简单的查询,仅列出符合您条件的用户名称

SELECT user FROM users u
WHERE NOT EXISTS (SELECT 1 FROM friends f WHERE u.uid IN (f.uid,f.fid) 
                                     AND 'xXXXxXXxxx' IN (f.uid,f.fid) )

答案 2 :(得分:0)

SELECT u.uid, 
         (SELECT COUNT(*) FROM friends f WHERE f.uid=u.uid AND f.fid = 'xXXXxXXxxx') c1,
         (SELECT COUNT(*) FROM friends f WHERE f.uid=u.uid AND f.uid = 'xXXXxXXxxx') c2
         FROM users u

WHERE (SELECT COUNT(*) FROM friends f WHERE f.uid=u.uid AND f.fid = 'xXXXxXXxxx')  = 0
OR (SELECT COUNT(*) FROM friends f WHERE f.uid=u.uid AND f.uid = 'xXXXxXXxxx') = 0