我试图编写一个SQL查询,在其中打印表1中的名称,性别以及参与者的数量。表1和表2中的id标签是相同的,所以我的想法是通过id标签将参与者分组,然后对他们进行计数。
$sql = 'SELECT T1.name, T1.gender, COUNT(T2.Participant_name) AS participant_count
FROM Table1 T1, Table2 T2
WHERE T1.Id = T2.Id
GROUP T2.Id';
该逻辑对我来说很有意义,但是似乎什么也没打印,我不确定哪里出了问题。
所需的输出:
< / p>
答案 0 :(得分:1)
在下面按两列T1.name,T1.gender进行分组
SELECT T1.name, T1.gender, COUNT(T2.Participant_name) AS participant_count
FROM Table1 T1 inner join Table2 T2
on T1.Id = T2.Id
GROUP T1.name, T1.gender
或者您可以尝试
select T1.name, T1.gender, T1.age,participant_count from
Table1 T1 inner join
( SELECT ID,COUNT(Participant_name) AS participant_count
FROM Table2
GROUP ID
)T2 on T1.Id = T2.Id
答案 1 :(得分:0)
您应该更改group语句,因为当您按要计数的列进行分组时,结果始终为1
SELECT T1.name, T1.gender, COUNT(T2.Participant_name) AS participant_count
FROM Table1 T1, Table2 T2
WHERE T1.Id = T2.Id
GROUP BY T1.name, T1.gender