【问题标题】:Get the result from the first table even if no match is found in the second table - MySQL即使在第二个表中找不到匹配项,也从第一个表中获取结果 - MySQL
【发布时间】:2013-02-08 19:02:03
【问题描述】:

我有两张表,结构如下

Table name = counter
ref_id INT NOT NULL
count INT NOT NULL

Table name = favs
disqus_id VARCHAR(32) NOT NULL
user_id INT NOT NULL
dormant VAHCHAR(10) NOT NULL

我运行这个查询 => SELECT count, dormant FROM counter AS c LEFT JOIN favs AS f ON c.ref_id = f.disqus_id WHERE ref_id = 'post_5' AND user_id = '1'.

但如果在第二个表favs 中没有找到匹配项,它不会返回任何行。我想要的是,如果找到结果,它应该返回两列,否则返回两列,第二列是NULL

我该怎么做?

【问题讨论】:

    标签: mysql select left-join


    【解决方案1】:

    ON 子句中用户的条件

    SELECT c.count, f.dormant 
    FROM   counter AS c 
           LEFT JOIN favs AS f 
              ON c.ref_id = f.disqus_id  AND f.user_id = '1'
    WHERE  c.ref_id = 'post_5' 
    

    或者如果仍然不起作用,移动两者:

    SELECT c.count, f.dormant 
    FROM   counter AS c 
           LEFT JOIN favs AS f 
              ON c.ref_id = f.disqus_id  AND 
                 f.user_id = '1' AND
                 c.ref_id = 'post_5' 
    

    【讨论】:

    • 太棒了!感谢@JW 的快速回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 2021-01-18
    • 2016-09-07
    相关资源
    最近更新 更多