如果没有找到结果,左连接默认为零?

时间:2015-02-22 13:36:15

标签: mysql

我的网站有一个帖子数据库。如果用户已经投票并且他们已经返回投票类型,我试图在查询内部返回。

这是我的查询

    SELECT p.*, 
        (SELECT Count(id) 
        FROM   comments AS c 
        WHERE  c.post = p.id) AS commentCount,
        v.type AS vote_type
   FROM   posts AS p 
   LEFT JOIN votes AS v
   ON v.post_id = p.id
   WHERE v.user_id = 1
   ORDER  BY timestamp DESC

虽然这确实会返回带有正确数据的字段vote_type,但它也会将结果限制为对该用户进行投票的结果。因此,它不会显示所有帖子,而只显示用户投票的帖子?如果没有找到结果,有没有办法让字段默认为0?

1 个答案:

答案 0 :(得分:0)

<强>问题:

尽管您使用了LEFT JOIN WHERE条款v.user_id = 1。所以其他所有人(user_id都是null)都没有被提取。

<强>解决方案:

WHERE子句中添加一个条件:

SELECT p.*, 
        (SELECT Count(id) 
        FROM   comments AS c 
        WHERE  c.post = p.id) AS commentCount,
        v.type AS vote_type
   FROM   posts AS p 
   LEFT JOIN votes AS v 
   ON v.post_id = p.id
   WHERE (v.user_id = 1 OR v.user_id IS NULL)
   ORDER  BY timestamp DESC

您也可以在JOIN本身

中指定它
SELECT p.*, 
        (SELECT Count(id) 
        FROM   comments AS c 
        WHERE  c.post = p.id) AS commentCount,
        v.type AS vote_type
   FROM   posts AS p 
   LEFT JOIN votes AS v 
   ON v.post_id = p.id AND v.user_id = 1
   ORDER  BY timestamp DESC