Home  >  Q&A  >  body text

How to GROUP BY multiple columns with multiple HAVING values ​​in MySQL?

I'm trying to create a mysql query to view the table where the search query is stored. This query attempts to get all rows matching the following criteria:

This query doesn't work but should outline what I'm trying to do:

SELECT 
  * 
FROM 
  `analytics` 
WHERE 
  `date` >= '2021-01-01' 
GROUP BY 
  `query` 
HAVING 
  COUNT(*) >= 3 
  AND 
GROUP BY 
  `user` 
HAVING 
  COUNT(*) >= 2 
ORDER BY 
  id DESC;

Sample data

id user Inquire date
1 5 What is a dog 2021-01-01
2 5 What is a dog 2021-01-01
3 6 What is a dog 2021-01-01
4 7 What is a dog 2021-01-01
5 7 What are brothers 2021-01-01

Example SQL

SELECT 
  * 
FROM 
  analytics 
WHERE 
  date >= '2021-01-01' 
GROUP BY 
  query 
HAVING 
  COUNT(*) >= 3 
  AND 
GROUP BY 
  user 
HAVING 
  COUNT(*) >= 2 
ORDER BY 
  id DESC;

Using the values ​​set in the query above, a single row should be returned for the query "What is a dogs", all other columns are unimportant.

I know you can GROUP BY separate columns with commas, but I can't seem to figure out how to set a different value for each column.

P粉775723722P粉775723722236 days ago404

reply all(1)I'll reply

  • P粉818317410

    P粉8183174102024-02-27 00:58:40

    You can set both conditions in the same HAVING clause:

    SELECT `query`
    FROM `analytics`
    WHERE `date` >= '2021-01-01'
    GROUP BY `query`
    HAVING COUNT(*) >= 3 AND COUNT(DISTINCT `user`) >= 2;

    reply
    0
  • Cancelreply