在 MySQL 中使用 Group By 将两个查询合并为一个
目前,我正在尝试获取一位用户的所有提交内容以及对特定提交内容的所有评论。我这样做的方式效率极低(循环内查询)。
我被告知要使用 Group By,但我不确定如何让它正常工作。
选择所有提交信息的第一个查询是:
SELECT
submissions.user_id,
submissions.id,
submissions.quote,
submissions.filename,
submissions.date_added,
submissions.views
FROM
`submissions`
WHERE
submissions.user_id = ?
ORDER BY
submissions.date_added
DESC
第二个(获取评论计数)是:
SELECT
count(id) AS `comments`
FROM
`comments`
WHERE
submission_id = '{$subId}'
这些工作,但由于它们会变得很慢,所以我尝试提出这个,但不确定如何正确执行它。
SELECT
submissions.user_id,
submissions.id,
submissions.quote,
submissions.filename,
submissions.date_added,
submissions.views,
COUNT(comments.id) as `comment`
comments.submission_id
FROM
submissions
LEFT JOIN
comments
ON
submissions.id=comments.submission_id
WHERE
submissions.user_id = ?
GROUP BY comment
关于如何解决这个问题有什么建议吗?我最初没有合并前两个查询的原因是因为 count 总是会为整个查询返回一行。
Currently, I'm trying to get all submissions from one user along with all comments on a particular submission. The way I am doing it is extremely inefficient (query inside of a loop).
I have been told to use Group By, but I'm not sure how to get it working properly.
The first query to select all submission info is:
SELECT
submissions.user_id,
submissions.id,
submissions.quote,
submissions.filename,
submissions.date_added,
submissions.views
FROM
`submissions`
WHERE
submissions.user_id = ?
ORDER BY
submissions.date_added
DESC
The second (to get the comment count) is:
SELECT
count(id) AS `comments`
FROM
`comments`
WHERE
submission_id = '{$subId}'
Those work, but since they will become slow, so I tried to come up with this, but am not sure how to execute it properly.
SELECT
submissions.user_id,
submissions.id,
submissions.quote,
submissions.filename,
submissions.date_added,
submissions.views,
COUNT(comments.id) as `comment`
comments.submission_id
FROM
submissions
LEFT JOIN
comments
ON
submissions.id=comments.submission_id
WHERE
submissions.user_id = ?
GROUP BY comment
Any suggestions on how to approach this? The reason I originally didn't combine the first two queries, is because count is always going to return one row for the whole query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个(我刚刚根据您对错误的评论在
comment
之后添加了一个逗号):Try this (I just added a comma after
comment
based upon your comment with the error):