LEFT JOIN 有 COUNT returns 个意外值
LEFT JOIN with COUNT returns unexpected value
我有两个表:
post:
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
我想查询 returns Igor 的类型 2、3 或 4 的 post 数量以及 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)
}
}
那么,如何做到这一点?
尝试:
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
这个怎么样。(根据您的查询 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'
问题是 p.type = 2 OR p.type = 3 OR p.type = 4
的计算结果为 1
或 0
,因此只有 2 个可能的不同计数。
要解决此问题,您可以使用 case
语句:
COUNT(DISTINCT case when p.type in (2,3,4) then p.id end)
我有两个表:
post:
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
我想查询 returns Igor 的类型 2、3 或 4 的 post 数量以及 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)
}
}
那么,如何做到这一点?
尝试:
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
这个怎么样。(根据您的查询 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'
问题是 p.type = 2 OR p.type = 3 OR p.type = 4
的计算结果为 1
或 0
,因此只有 2 个可能的不同计数。
要解决此问题,您可以使用 case
语句:
COUNT(DISTINCT case when p.type in (2,3,4) then p.id end)