mysql - 带 COUNT 的 LEFT JOIN 返回意外值

标签 mysql join count left-join inner-join

我有两个表:

发布:

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)
  }
}

那么,如何做到这一点?

最佳答案

问题是 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)

关于mysql - 带 COUNT 的 LEFT JOIN 返回意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36538007/

相关文章:

MySQL 服务器已经不再支持简单的选择查询

mysql - 从另一个表中检索数据

c# - 此 LINQ JOIN 是否存在某种语法错误?

php - 如何从一系列序列号中获取并在溢出后翻转

mysql - SQL 查询计算记录中单词的实例

MySQL - 根据提交的工作选择用户名(二变量)

php - 如何计算php中包括空格和正则表达式在内的所有字符?

sql - 我可以使用什么 SQL 从我的付款数据中检索计数?

mysql - 加载 CSV 时设置插入时间戳

mysql - 如何根据特定列计算重复行?