2013-08-17 40 views
0

假設我有很多標記的實體(例如帶有標記的博客帖子)存儲在SQL數據庫中。例如:如何從數據庫檢索樣本?

 
post1: work 
post2: work, programming, java, work 
post3: work, programming, sql 
post4: vacation, photo 
post5: vacation 
post6: photo 

還假設我有標籤

 
work, vacation 

列表現在我想獲得一個職位大小爲2 樣品,即兩個職位從列表標籤。例如

 
sample1: post1 and post2 
sample2: post1 and post4 
sample3: post2 and post5 

另外我想在樣品包含列表中的所有標籤。請注意,sample1不符合此要求,因爲樣本實體的標記集不包含列表中的標記vacation

我想所有的標籤事件都是平等的。讓我們考慮規模的2個樣本4

 
sample1: post1, post2, post3, post6 
sample2: post1, post3, post4, post5 

注意,由於標籤work在它發生3次,vacation只發生一次sample1不符合這一要求。

我的問題是:如何設計關係數據庫和SQL查詢來檢索給定大小的樣本?

回答

1

如果你想有標籤以逗號分隔的列表中的所有帖子:

select postid 
from post_tags 
where find_in_set(tagid, @LIST) > 0 
group by postid 
having count(distinct tagid) = 1+length(@LIST) - length(replace(',', @LIST, '')); 

如果你想他們的只是一個「樣本」:

select postid 
from (select postid 
     from post_tags 
     where find_in_set(tagid, @LIST) > 0 
     group by postid 
     having count(distinct tagid) = 1+length(@LIST) - length(replace(',', @LIST, '')) 
    ) t 
order by rand() 
limit 5 
+0

謝謝!你能解釋一下嗎?有數量(獨特的tagid)= 1 +長度(@LIST) - 長度(替換(',',@ LIST,''))'東西? – Michael

+1

@Michael。 。 。這是計數字符串中元素的數量。這是數字逗號加一。 –