gpt4 book ai didi

php - SQL:从表中选择列并比较+计数

转载 作者:行者123 更新时间:2023-11-29 03:07:18 25 4
gpt4 key购买 nike

我正在改进我的 php 脚本,它有两个简单的 sql 查询。我想做的是将两个查询合并为一个。

第一个查询:

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、作者、正文、发布日期),如果这对了解有帮助的话。

我尝试了不同的方法。像这样:

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。

关于php - SQL:从表中选择列并比较+计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13355635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com