在mysql中显示计数值和多行

时间:2014-03-19 10:26:01

标签: mysql sql

我确实试图通过谷歌搜索获得答案,但我无法找到解决方案。

我实际上有两张桌子。

这是假设学生表

id  | sname | cid
 1      a      1
 2      b      2
 3      c      2
 4      d      3
 5      e      4
 6      f      3
 7      g      4
 8      h      3

这是班级表

id  | sname 
 1      c1    
 2      c2    
 3      c3    
 4      c4    

我想要如下结果:

Result:

id  | cname | sname | count
 1      c1      a       1
 2      c2      b       2
 3      c2      c       2
 4      c3      d       3
 1      c4      e       2
 2      c3      f       3
 3      c4      g       2
 4      c3      h       3

正如您所看到的,结果将如上所述,所有学生姓名将与课程名称和&伯爵就是这样。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT * FROM
((SELECT C.id,C.sname as cname,S.sname as sname
FROM class C INNER JOIN students S on C.id=S.cid) T1
LEFT JOIN
(Select C.id,count(S.cid) as count
FROM class C INNER JOIN students S on C.id=S.cid
GROUP BY C.id) T2 on T2.id=T1.id)
ORDER BY sname

结果:

ID  CNAME   SNAME   COUNT
1   c1      a       1
2   c2      b       2
2   c2      c       2
3   c3      d       3
4   c4      e       2
3   c3      f       3
4   c4      g       2
3   c3      h       3

请参阅SQL Fiddle中的结果。

<强>解释

内部查询的第一部分选择id,cname和sname。第二部分选择计数。在外部查询中,我们只是加入它们。

答案 1 :(得分:0)

使用子查询进行连接的连接应该:

SELECT
    s.id `id`,
    c.sname `cname`,
    s.sname `sname`,
    (SELECT COUNT(1) FROM students WHERE students.cid = c.id) `count`
FROM
    students s
    LEFT JOIN class c ON s.cid = s.id

答案 2 :(得分:0)

 SELECT S.ID AS ID , C.SNAME AS CNAME , S.SNAME AS SNAME , CNT.COUNT AS COUNT
 FROM STUDENTS S ,  CLASS C , (
                               SELECT S.CID AS CID , COUNT(*) AS COUNT
                               FROM STUDENTS S
                               GROUP BY S.CID
                               ) AS CNT

 WHERE S.CID = C.ID AND CNT.CID = C.ID