-1

I'm struggling to find a way to combine these two queries into one so that only one table is viewed. I want to display the top 5 and bottom 5 categories based on the number of members in each category.

SELECT 
    category_name,
    members
From category c
JOIN grp g ON c.category_id=g.category_id
GROUP by category_name
ORDER BY members DESC
LIMIT 5;

SELECT 
    category_name,
    members
From category c
JOIN grp g ON c.category_id=g.category_id
GROUP by category_name
ORDER BY members
LIMIT 5;

I've tried union and multiple select statements but always end up with an error for "subquery returns more than 1 row" or inccorect syntax. Any help would be appreciated.

3
  • The answer is: use UNION, or UNION ALL. I wonder what you did when you got the error.
    – Luuk
    Jun 26, 2021 at 9:51
  • see: stackoverflow.com/a/15024011/724039
    – Luuk
    Jun 26, 2021 at 9:57
  • I removed "MYSQL Work Bench" from the title. Because MYSQL Work Bench is a tool to connect to a MySQL database, and should not have influence on the syntax of a SQL query.
    – Luuk
    Jun 26, 2021 at 10:14

1 Answer 1

1

If you are going to do unions with ORDER and LIMIT clauses, you will have to "hide" these clauses within subqueries:

SELECT * FROM (
    SELECT 
        category_name,
        members
    From category c
    JOIN grp g ON c.category_id=g.category_id
    GROUP by category_name
    ORDER BY members DESC
    LIMIT 5
) SQ1
UNION
SELECT * FROM (
    SELECT 
        category_name,
        members
    From category c
    JOIN grp g ON c.category_id=g.category_id
    GROUP by category_name
    ORDER BY members
    LIMIT 5
) SQ2
3
  • That worked. I think i was missing the second sellect * after the union. Instead of using a union, how would you display these side by side? Jun 26, 2021 at 23:14
  • You should open up a new question and explain more clearly what "side by side* would look like because right now I would only be guessing as to what you are looking for. But be sure to specify which release of MySQL you have because the solution will probably depend on that.
    – Booboo
    Jun 26, 2021 at 23:44
  • Thanks. Will do. Unfortunately, I'll have to wait since my original question got downvoted. Jun 27, 2021 at 0:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.