A
A
alesto2011-04-22 22:23:12
MySQL
alesto, 2011-04-22 22:23:12

I don’t know how to write a query in Mysql, I won’t describe it in the title. Look under the cut

There is a simple table
id,tag_id,post_id
As you might guess, it displays the relationship between a tag and a blog post. How can I display a post that has multiple tags? For example, several rows in a table might look like this:
1 27 5
2 28 5
3 29 5

How to select records that have all 3 tags? 27,28,29;

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
niko83, 2011-04-22
@niko83

SELECT post_id, count(id) as count from post_tag where tag_id IN (27,28,29) GROUP BY post_id HAVING count = 3;

P
Pavel Chipak, 2011-04-22
@reket

SELECT post_id FROM table GROUP BY post_id HAVING COUNT(id)>=3

M
MiXei4, 2011-04-22
@MiXei4

The simplest
SELECT t1.* FROM table as t1, table as t2, table as t3 WHERE (t1.tag_id=27 and t2.tag_id=28 and t3.tag_id=29) and (t1.post_id = t2.post_id) and ( t2.post_id = t3.post_id);
You can probably improve the query with the help of joins and so on ...

P
plaha, 2011-04-23
@plaha

SELECT post_id, GROUP_CONCAT(tag_id) as gr_tag FROM table GROUP BY post_id HAVING gr = '27,28,29'
ORDER BY post_id, tag_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question