[英]SQL: Select colums from tables and compare + count
我正在改进具有两个简单sql查询的php脚本。 我想做的是将两个查询合并为一个。
第一个查询:
SELECT categories.*, entries.*
FROM categories, entries
WHERE entries.cat_id = categories.cat_id
ORDER BY dateposted ASC
LIMIT 5;
第二查询:
SELECT comments.*
FROM comments
WHERE comments.entry_id = '. $row['id'].';
这两个分开工作时效果很好。 我只需要将它们组合成一个(仍然很简单,请不要使用UNION或INNER JOIN),并可能在查询中为特定条目计算大量注释。 另外,我的“评论”表有五列(comment_id,post_id,author,body,dateposted),如果有帮助的话。
我尝试了不同的方法。 像这样:
SELECT categories.*, entries.*, COUNT(comments.entry_id) AS comm_num
FROM categories, entries, comments
WHERE entries.cat_id = categories.cat_id
AND comments.entry_id = entries.id
ORDER BY dateposted ASC LIMIT 5;
不工作...
任何帮助将不胜感激。
您的第一个查询本质上是一个联接,并且可能不会更快。 您可以查询条目(同时显示相应的类别信息),如下所示:
SELECT entries.*, categories.*
FROM entries
LEFT JOIN categories ON entries.cat_id = categories.cat_id
ORDER BY dateposted ASC
LIMIT 5;
同样,听起来您实际上并不想返回此查询中的每个注释行,而只是获取每个“条目”的注释计数。 为此,您可以执行以下操作:
SELECT entries.*, categories.*, COUNT(comments.comment_id) AS comm_num
FROM entries
LEFT JOIN categories on entries.cat_id = categories.cat_id
LEFT JOIN comments on comments.entry_id = entries.entry_id
GROUP BY entries.entry_id
ORDER BY dateposted ASC
LIMIT 5;
请注意,COUNT函数是对注释ID而不是条目ID进行计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.