2010-05-18 272 views
4

我有兩個表格:照片和photograph_tags。 Photograph_tags包含一個名爲photograph_id的列(照片中的ID)。您可以爲一張照片製作多個標籤。我有一個與三個標籤相關的照片行:男孩,小溪和水。但是,運行以下查詢返回0行這個SQL查詢有什麼問題?

SELECT p.* 
FROM photographs p, photograph_tags c 
WHERE c.photograph_id = p.id 
AND (c.value IN ('dog', 'water', 'stream')) 
GROUP BY p.id 
HAVING COUNT(p.id)=3 

此查詢有問題嗎?

My tables look like so 
----------------------- 
photographs 
----------------------- 
id | title | location 
------------------------ 
7 | asdf | c:\... 


----------------------- 
photograph_tags 
----------------------- 
id | photograph_id | value 
1 | 7    | dog 
2 | 7    | water 
3 | 7    | stream 
4 | 7    | mountains 

I want to pull all photograph rows that relate to at least all three of the searched tags 

回答

1

使用您指定的3個標籤(或更多)獲取所有照片。從標籤開始並加入照片。

select 
p.id 
from photographs p 

left join photograph_tags c 
on p.id = c.photograph_id 
and c.value IN ('dog', 'water', 'stream') 

group by p.id 

having count(c.value) >= 3 

測試上面的代碼:

create table #photograph_tags (
    photograph_id INT, 
    value varchar(50) 
) 

create table #photographs (
    id int 
) 

insert into #photographs values (7) 
insert into #photographs values (8) 

insert into #photograph_tags values (7, 'dog') 
insert into #photograph_tags values (7, 'water') 
insert into #photograph_tags values (7, 'stream') 
insert into #photograph_tags values (7, 'mountains') 
insert into #photograph_tags values (8, 'stream') 
insert into #photograph_tags values (8, 'mountains') 

select * from #photographs 
select * from #photograph_tags 

select 
    p.id 
from #photographs p 

left join #photograph_tags c 
on p.id = c.photograph_id 
and c.value IN ('dog', 'water', 'stream') 

group by p.id 

having count(c.value) >= 3 


drop table #photograph_tags 
drop table #photographs 
+0

這個查詢顯示多個相同的行多次 – ThinkingInBits 2010-05-18 06:09:58

+0

和一些沒有全部三個 – ThinkingInBits 2010-05-18 06:10:19

+0

@ThinkingInBits:你去了,更新了SQL,所以照片必須有所有標記 – 2010-05-18 06:31:00

0
SELECT p.* FROM photographs p join 
(select id, COUNT(id) as TagCount 
    FROM Photograph_Tags c 
    WHERE c.value IN ('dog', 'water', 'stream') 
    group by id) 
    as TagCounts on p.id = TagCounts.id 
WHERE TagCount = 3 
0

SELECT P * FROM照片p WHERE(c.value IN( '狗', '水', '流') ) AND(SELECT COUNT(*) FROM photograph_tags c
WHERE c.photograph_id = p.id)> = 3;

會給你帶有至少三個標籤的照片。