Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: how to select groups having certain values?

Say there is such table:

mysql> SELECT * FROM tags;
+---------+--------+
| post_id | tag_id |
+---------+--------+
|       1 |      2 |
|       1 |      3 |
|       1 |      1 |
|       2 |      1 |
|       2 |      2 |
+---------+--------+
5 rows in set (0.00 sec)

Field names are pretty self-explanatory. I want to select post_ids that have both 1 and 3 tag_ids, so in this example it's only 1. I thought of something like SELECT post_id FROM tags GROUP BY post_id HAVING ... After having I'd like to list tag_ids that are present in this group. How do I do that?

like image 662
htf Avatar asked Jun 21 '10 09:06

htf


People also ask

Can we use SELECT * with GROUP BY?

You cannot write select inside the Group by clause.

Can we use GROUP BY with where clause?

GROUP BY clause is used with the SELECT statement. In the query, GROUP BY clause is placed after the WHERE clause.

How do I SELECT a specific record in MySQL?

MySQL SELECT specific rows When a user wants to retrieve some individual rows from a table, a WHERE clause has to be added with the SELECT statement immediately followed by a condition. Here * indicates all columns.


2 Answers

If there aren't any unique constraints try:

SELECT post_id 
FROM tags 
WHERE tag_id = 1 OR tag_id = 3 
GROUP BY post_id 
HAVING count(DISTINCT tag_id) = 2;

Or use this HAVING clause, if trying to detect only two tag_id values:

HAVING MIN(tag_id) <> MAX(tag_id)

If post_id and tag_id both have an unique constraint, this should work too:

SELECT post_id 
FROM tags 
WHERE tag_id = 1 OR tag_id = 3 
GROUP BY post_id 
HAVING count(*) = 2;
like image 71
rudi-moore Avatar answered Oct 28 '22 00:10

rudi-moore


SELECT post_id
  FROM ( SELECT post_id,
                count(tag_id) AS counter
           FROM tags
          WHERE tag_id IN (1,3)
          GROUP BY post_id
       )
 WHERE counter = 2

Use GROUP_CONCAT() for the second part of your question

SELECT post_id,
       GROUP_CONCAT(tag_id ORDER BY tag_id ASC SEPARATOR ',')
  FROM tags
like image 40
Mark Baker Avatar answered Oct 28 '22 00:10

Mark Baker