MySQL数据透视表计数

时间:2016-06-12 08:32:31

标签: mysql pivot counting

我有三张桌子:

users
------
user_id
name

subjects
--------
subject_id
name

pivot_user_subject
------------------
user_id
subject_id

我在此查询中显示主题和用户名:

SELECT a.name User, c.name Subject 
FROM users a, pivot_user_subject b, subjects c 
WHERE a.user_id = b.user_id AND c.subject_id = b.subject_id;

并且效果很好。但现在我需要显示用户有多少科目。

示例输出:

User      Subjects                      Subjects_count
Juan      Math, Biology, Spanish               3
Rosa      NULL                                 0
Rodrigo   Math                                 1

有关如何仅使用SQL查询完成输出的任何想法?感谢。

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT u.name, GROUP_CONCAT(s.name), COUNT(s.subject_id) as Subject_count
FROM users u
LEFT JOIN  pivot_user_subject us ON u.user_id = us.user_id
LEFT JOIN subjects s ON s.subject_id = us.subject_id
GROUP BY u.user_id, u.name

SQL Fiddle

答案 1 :(得分:0)

如果c.name,分隔,或者它只是一个主题,或者它只是null,您可以尝试关注;)

SELECT
    a.name AS User,
    c.name AS Subjects,
    IF(c.name IS NULL, 0, LENGTH(c.name) - LENGTH(REPLACE(c.name, ',', '')) + 1) AS Subjects_count
FROM users a, pivot_user_subject b, subjects c
WHERE a.user_id = b.user_id AND c.subject_id = b.subject_id;