sql将2个查询与JOIN组合在一起

时间:2012-01-12 02:21:49

标签: sql join

我知道循环SQL查询并不是一个好主意,因此我想将这两个查询更改为一个。

在JOINs上不太好,我正在努力想出如何合并这两个,并且在那里有DISTINCT。

$sql_result2 = mysql_query("SELECT DISTINCT gang FROM turfs WHERE city='$city'", $db);  
while ($rs2 = mysql_fetch_array($sql_result2)) {

    $sql_result3 = mysql_query("SELECT (SELECT COUNT(*) FROM turfs WHERE city='$city' AND gang=g.id) as count, g.id, g.name, g.color FROM gangs g WHERE g.id='$rs2[gang]'", $db); 
    $rs3 = mysql_fetch_array($sql_result3);

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

加入并分组如下:

select   count(*) as count, G.ID, G.NAME, G.COLOR
from     GANGS G join TURFS T on T.GANG = G.ID
where    CITY = '$city'
group by G.ID, G.NAME, G.COLOR