bob_cobb
bob_cobb

Reputation: 2269

Combining two queries into one using Group By in MySQL

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.

Upvotes: 1

Views: 558

Answers (1)

Jacob Eggers
Jacob Eggers

Reputation: 9332

Try this (I just added a comma after comment based upon your comment with the error):

    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

Upvotes: 2

Related Questions