我的意思是说:
想象一下这些表:
Table article_status: Table users:
userid | article | status id | name
--------+---------+------- ---+------
1 | 1 | 1 1 | Peter
1 | 2 | 2 2 | Bob
2 | 3 | 1
2 | 4 | 1
2 | 5 | 2
2 | 6 | 2
2 | 7 | 3
我想要得到的是按用户状态编号分组的所有项目的计数。可能的状态值的数量是已知的 (4)。
示例结果users.id = 2
:
userid | name | s1_count | s2_count | s3_count | s4_count |
-------+------+----------+----------+----------+----------+
2 | Bob | 2 | 2 | 1 | 0 |
我试过的:
SELECT
u.id AS userid
, u.name
, COUNT(s1.status) AS s1_count
, COUNT(s2.status) AS s2_count
, COUNT(s3.status) AS s3_count
, COUNT(s4.status) AS s4_count
FROM users AS u
INNER JOIN article_status AS s1 ON s1.userid = u.id AND s1.status = 1
INNER JOIN article_status AS s2 ON s2.userid = u.id AND s2.status = 2
INNER JOIN article_status AS s3 ON s3.userid = u.id AND s3.status = 3
INNER JOIN article_status AS s4 ON s4.userid = u.id AND s4.status = 4
WHERE u.id = :uid
LIMIT 1
但这不起作用(为什么?)而且看起来非常不理想。有任何想法吗?