在MySQL中使用Group By将两个查询合并为一个

时间:2011-06-15 16:34:18

标签: mysql sql count 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总是为整个查询返回一行。

1 个答案:

答案 0 :(得分:2)

尝试此操作(我根据您对错误的评论,在comment之后添加了一个逗号):

    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 submissions.user_id,
        submissions.id,
        submissions.quote,
        submissions.filename,
        submissions.date_added,
        submissions.views,
        comments.submission_id