I have a 3 tables with the following data in MySQL
table 表
id | groupId | name |
-----------------------------
1 | 1 | tag1 |
2 | 1 | tag2 |
3 | 1 | tag3 |
4 | 1 | tag4 |
groupId column here is unimportant right now.
table 表
id | name |
----------------------
1 | practice 1 |
2 | practice 2 |
3 | practice 3 |
4 | practice 4 |
and a bridge between the two ( table) 表)
id | practiceId | tagId |
-----------------------------------
1 | 1 | 1 |
2 | 1 | 2 |
3 | 1 | 3 |
4 | 2 | 1 |
But when I try to use the query:
SELECT practice.name
FROM practice
INNER JOIN practiceTag ON practiceTag.practiceId = practice.id
INNER JOIN tags ON practiceTag.tagId = tags.id
WHERE (tags.id = "1"
AND tags.id = "2"
AND tags.id = "3")
it doesn't return anything. And thats ok, since I know my query is kinda messed up. But thats as closest as I can get to show you, what I would like my query to do.
I've searched the forums and find out that I can use a group_concat. But I just can't get it to work.
Any help would be appreciated.
Thanks, Sebastian
You in
clause not and
SELECT practice.name
FROM practice
INNER JOIN practiceTag ON practiceTag.practiceId = practice.id
INNER JOIN tags ON practiceTag.tagId = tags.id
WHERE tags.id in ( '1', '2', '3') ;
if the id is numeric
SELECT practice.name
FROM practice
INNER JOIN practiceTag ON practiceTag.practiceId = practice.id
INNER JOIN tags ON practiceTag.tagId = tags.id
WHERE tags.id in ( 1, 2, 3) ;
the query is equivalent
SELECT distinct practice.name
FROM practice
INNER JOIN practiceTag ON practiceTag.practiceId = practice.id
INNER JOIN tags ON practiceTag.tagId in (1,2,3)
And if you want only the practice.name when all the 3 tagsId match the you should use temp table for getting the join table
SELECT distinct practice.name
FROM practice
inner join (
select practiceId from
( select distinct practiceTag.practiceId as praticeId, practiceTag.tagId as tagId
from tags ) as t1
where tagId in (1,2,3)
having count(*) > 2
group by praticeId ) as t2;
I think your tags.id column is integer not string, so your sql query would be like this:
SELECT practice.name
FROM practice
INNER JOIN practiceTag ON practiceTag.practiceId = practice.id
INNER JOIN tags ON practiceTag.tagId = tags.id
WHERE tags.id in (1,2,3);
In your WHERE
part you ask for results that have id
1, 2 and 3 at the same time.
Replace the AND
in your WHERE
with OR
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.