MySQL 枢轴 table 计数

MySQL pivot table 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 查询来完成该输出吗?谢谢。

如果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;

试试这个

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