【问题标题】:LEFT JOIN with COUNT returns unexpected value带有 COUNT 的 LEFT JOIN 返回意外值
【发布时间】:2016-07-31 23:37:24
【问题描述】:

我有两张桌子:

发帖

id | body   | author | type | date
1  | hi!    | Igor   | 2    | 04-10
2  | hello! | Igor   | 1    | 04-10
3  | lol    | Igor   | 1    | 04-10
4  | good!  | Igor   | 3    | 04-10
5  | nice!  | Igor   | 2    | 04-10
6  | count  | Igor   | 3    | 04-10
7  | left   | Igor   | 3    | 04-10
8  | join   | Igor   | 4    | 04-10

点赞

id | author | post_id
1  | Igor   | 2
2  | Igor   | 5
3  | Igor   | 6
4  | Igor   | 8

我想做一个查询,返回 Igor 发表的类型为 2、3 或 4 的帖子数量以及 Igor 发表的点赞数,所以,我做到了:

SELECT COUNT(DISTINCT p.type = 2 OR p.type = 3 OR p.type = 4) AS numberPhotos, COUNT(DISTINCT l.id) AS numberLikes
FROM post p
LEFT JOIN likes l
ON p.author = l.author
WHERE p.author = 'Igor'

预期的输出是:

array(1) {
  [0]=>
  array(2) {
    ["numberPhotos"]=>
    string(1) "6"
    ["numberLikes"]=>
    string(2) "4"
  }
}

但是输出是:

array(1) {
  [0]=>
  array(2) {
    ["numberPhotos"]=>
    string(1) "2"
    ["numberLikes"]=>
    string(2) "4" (numberLikes output is right)
  }
}

那么,该怎么做呢?

【问题讨论】:

  • 您想要帖子的点赞数?还是一切的总和?
  • @llouk 没有。我想要 Igor 的点赞数。 numberLikes 输出正确,问题出在numberPhotos 输出

标签: mysql join count left-join inner-join


【解决方案1】:

问题在于 p.type = 2 OR p.type = 3 OR p.type = 4 的计算结果为 10,因此只有 2 个可能的不同计数。

要解决此问题,您可以使用case 语句:

COUNT(DISTINCT case when p.type in (2,3,4) then p.id end)

【讨论】:

  • 根据你的回答,numberPhotos 输出是 3 而不是 6
  • @Igor 我进行了更正。最后一部分应该是then p.id 而不是then p.type
【解决方案2】:

这个怎么样。(对您的查询 sql 进行一些修改)。

SELECT COUNT(DISTINCT p.type = 2) + COUNT(DISTINCT p.type = 3) + COUNT(DISTINCT p.type = 4) AS numberPhotos,       COUNT(DISTINCT l.id) AS numberLikes
FROM post p
LEFT JOIN likes l
ON p.author = l.author
WHERE p.author = 'Igor'

【讨论】:

    【解决方案3】:

    试试:

    SELECT (SELECT COUNT(*) FROM post p WHERE p.type = 2 OR p.type = 3 OR p.type = 4 AND p.author = 'Igor') AS numberPhotos, (SELECT COUNT(*) FROM likes l WHERE l.auhtor = 'Igor') AS numberLikes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多