如何从另一个表中获取每个值的计数?

时间:2008-10-24 01:01:44

标签: php mysql

我有一张志愿者_2009表,列出了所有志愿者和一个场地表,列出了志愿者可以分配到的场地,他们只被分配到一个。

我想要做的是打印出分配到每个场地的志愿者人数。

我希望它打印出来像这样:

地点名称:志愿者数量

表:志愿者_2009 列:id,name,venue_id

表:场地 columns:id,venue_name

它们与volunteers_2009.venue_id = venues.id

相关

这就是我所拥有的,但它无法正常工作。

$sql = "SELECT venues.venue_name as 'Venue', COUNT(volunteers_2009.id) as 'Number Of 
Volunteers' FROM venues ven JOIN volunteers_2009 vol ON 
(venues.id=volunteers_2009.venue_id) GROUP BY venues.venue_name ORDER BY
venues.venue_name ASC";

$result = mysql_query($sql);

while(list($name,$vols) = mysql_fetch_array($result)) {
    print '<p>'.$name.': '.$vols.'</p>';
}

2 个答案:

答案 0 :(得分:2)

不是MySQL的人,所以这可能是错的,但当你给你的表别名时,你不需要用这个名称来引用它。

$sql = "SELECT ven.venue_name as 'Venue', COUNT(vol.id) as 'Number Of 
Volunteers' FROM venues ven JOIN volunteers_2009 vol ON 
(ven.id=vol.venue_id) GROUP BY ven.venue_name ORDER BY ven.venue_name ASC";

答案 1 :(得分:0)

$query = "SELECT ven.venue_name AS 'Venue', count(*) AS 'Number of venues'
         FROM volunteers_2009 AS vol, venues AS ven WHERE vol.venue_id = ven.id 
         GROUP BY ven.venue_name";