php mysql左连接计数列相同的id

时间:2013-10-10 16:34:27

标签: php mysql sql

如何左表连接表Aste所有帐户concorso_id等于表concorsi的id?

表concorsi

id  name
1   car     
2   bike
3   boat

表Aste

id  concorso_id
 1   1    
 2   1
 3   2
 4   2
 5   1
 6   3

我想要这个结果

id   name    count
1    car     3
2    bike    2
3    boat    1

3 个答案:

答案 0 :(得分:2)

与group by的简单连接应该有效:

select c.id, c.name, count(a.*) total
from concorsi c
    left join aste a on c.id = a.concorso_id
group by c.id

答案 1 :(得分:0)

SELECT
  concorsi.id,
  concorsi.name,
  COUNT(Aste.id) AS count
FROM
  concorsi
  LEFT JOIN Aste ON
    concorsi.id=Aste.concorsi_id
GROUP BY
  concorsi.id

有关JOINS工作方式的更多参考,请参阅文章here,并始终记得再次参考MySQL man

答案 2 :(得分:-1)

select c.id, c.name, count(concorso_id) 
from table concorsi as c, Aste as a 
where c.id=a.concorso_id group by concorso_id;