我有一张看起来像这样的照片表:
id title rating photopath
1 myself 7.0 /photopath1.jpg
2 cat 8.0 /photopath2.jpg
3 dog 6.0 /photopath3.jpg
4 girlfriend 5.0 /photopath4.jpg
和标签表:
id tag_name photo_id
1 selfie 1
2 sun 1
3 nature 2
4 relax 2
5 loyal 3
6 journal 3
7 selfie 4
8 sun 4
9 problems 4
我想打电话给所有带有标签的照片" selfie"和" sun"。我该怎么做?
答案 0 :(得分:2)
这是" set-within-sets"查询。我喜欢使用聚合和having
:
select p.id
from photos p join
tags t
on p.id = t.photo_id
group by p.id
having sum(case when tag_name = 'selfie' then 1 else 0 end) > 0 and
sum(case when tag_name = 'sun' then 1 else 0 end) > 0;
这种方法的便利之处在于很容易添加更多条件(例如另一个标签)或者反转条件(例如"自拍" s没有" sun")
答案 1 :(得分:1)
select p.*
from photo p
join (select p.id
from photo p
join tag t
on p.id = t.photo_id
where t.tag_name in ('selfie', 'sun')
group by p.id
having count(*) = 2) x
on p.id = x.id
小提琴: http://sqlfiddle.com/#!2/5c95c2/2/0
输出:
| ID | TITLE | RATING | PHOTOGRAPH |
|----|------------|--------|------------------|
| 1 | myself | 7 | /photograph1.jpg |
| 4 | girlfriend | 5 | /photograph4.jpg |
答案 2 :(得分:0)
SELECT *
FROM Photos
WHERE EXISTS (SELECT 1
FROM Tag_Table
WHERE photo_id = Photos.id
AND tag_name = 'selfie'
)
AND EXISTS (SELECT 1
FROM Tag_Table
WHERE photo_id = Photos.id
AND tag_name = 'Sun'
)