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_id
s that have both 1 and 3 tag_id
s, 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_id
s that are present in this group. How do I do that?
You cannot write select inside the Group by clause.
GROUP BY clause is used with the SELECT statement. In the query, GROUP BY clause is placed after the WHERE clause.
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.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With