TL; DR:有没有更好的方法呢?代码有点乱,但它适用于我的应用程序
id是主题ID,id2是回复ID
$dn1 = mysql_query(
'select c.id, c.name, c.description,c.position,c.bild,
(
select count(t.id)
from topics as t
where t.parent=c.id and t.id2=1
) as topics,
(
select count(t2.id)
from topics as t2
where t2.parent=c.id and t2.id2!=1
) as replies
from categories as c
group by c.id
order by c.position asc'
);
$nb_cats = mysql_num_rows($dn1);
while($dnn1 = mysql_fetch_array($dn1)
答案 0 :(得分:0)
对我而言,您的查询似乎与此相同:
select c.id, c.name, c.description, c.position, c.bild,
count(t1.id) as topics, count(t2.id) as replies
from categories as c
inner join topics as t1 on t1.parent = c.id and t1.id2 = 1
inner join topics as t2 on t2.parent = c.id and t2.id2 != 1
group by c.id
order by c.position asc
我认为MySQL查询规划器对它有类似的看法。
如果您认为这种情况更具可读性,可以将涉及id2
字段的条件移到WHERE
子句中。
此查询将仅返回至少包含一个主题和至少一个响应的类别。如果您还需要没有主题或回复的类别,那么您必须将INNER JOIN
替换为LEFT JOIN
s,将保留替换为id2
上的条件