来自同一个表的mysql计数和来自另一个表的数据

时间:2011-01-14 05:35:57

标签: sql mysql

我想通过提供replyid来显示注册用户的名称和regid的计数,我不知道获得结果的正确查询是什么

以下是表格。

details_table

id  regid  replyid  
-------------------
1   1      2  
2   1      3  
6   2      4  
5   3      4  
8   2      5  
9   3      5  
10  4      5  
11  5      5  
12  2      6  
13  6      6  
14  4      6  
15  7      7  
16  8      7  
17  9      7  
18  10     8  
19  2      9  
20  2      10  
21  11     10  
22  12     10  

reg_table

id  regname  
---------------
1      Sam  
2      Ash  
3      Tina  
4      Rohny  
5      Martin  
6      Natasha
7      Natalia
8      Kim
9      Alex
10     John  
11     Neil  
12     Peter  

因此,如果在where子句中从details_table中选择了replyid ie(10),则假设从reg_table中显示2,11,12 ie(Ash,Neil,Peter),其中Ash = 5,Neil = 1,彼得= 1

4 个答案:

答案 0 :(得分:1)

SELECT a.id, a.regname, COUNT(1)
  FROM reg_table a, details_table b,
    details_table c
 WHERE b.replyid=10
   AND b.regid = a.id
     AND c.regid = a.id
GROUP   BY a.id, a.regname

答案 1 :(得分:0)

SELECT r.regid, r.regname, count(*)
FROM (
  SELECT DISTINCT regid
  FROM details_table
  WHERE replyid = 10
 ) rg 
 JOIN reg_table r ON rg.regid = r.regid
 JOIN details_table d ON r.regid = d.regid
GROUP BY r.regid

答案 2 :(得分:0)

试试这个

select count(dt.regid) as cnt, regname from details_table dt, reg_table rt where dt.regid = rt.Regid and dt.replyid = 10 group by rt.Regid

答案 3 :(得分:-1)

SELECT reg_table.regname, count(*) from reg_table,  details_table where details_table.regid = reg_table.id GROUP BY reg_table.id