2013-05-02 39 views
0

我有一個帶有2個字段的「Posts_Tags」表。找不到logiq mysql請求SELECT ... IN

post_id tag_id 
1   1 
1   4 
1   9 
2   1 
2   4 
2   7 
3   2 
3   4 

一表 「標籤」 用3種

tag_id type  name 
1   geoloc  Paris 
2   geloc  Rome 
3   geoloc  London 
4   paint  Abby 
5   paint  Martin 
6   paint  Dupont 
7   designer Paulo 
8   designer Stefy 
9   designer Michel 

我想獲得的POST_ID與一些​​tags_id。

我已經提出了一個簡單的請求,以獲得所有帖子ID與以下標籤:巴黎,羅馬。

$arrray_in = array(1, 2); //This array is generated and can contain all Tags Ids, this is example value, maybe can i 10 values or more... 
SELECT * FROM posts_tags WHERE tag_id IN($array_in) GROUP BY post_id 

我想只能通過以下標籤Paris(geoloc)和Abby(paint)獲得post_id。這個請求不給我好成績(返程POST_ID:1,2,3,我想只有POST_ID:1,2)

$arrray_in = array(1, 2); //This array is generated and can contain all Tags Ids, this is example value, maybe can i 10 values or more... 
    SELECT * FROM posts_tags WHERE tag_id IN($array_in) GROUP BY post_id 

回答

0

您可以使用下面的方法獲取只有這些標籤的帖子:

SELECT pt.post_id 
FROM posts_tags pt 
WHERE pt.tag_id IN(1, 4) 
GROUP BY pt.post_id 
having count(distinct pt.tag_id) =2; 

請參閱SQL Fiddle with Demo

如果要返回有關職位的詳細信息,那麼你canuse:

select * 
from posts_tags pt1 
inner join tags t 
    on pt1.tag_id = t.tag_id 
    and t.tag_id in (1, 4) 
where exists (SELECT pt.post_id 
       FROM posts_tags pt 
       WHERE pt.tag_id IN(1, 4) 
       and pt1.post_id = pt.post_id 
       GROUP BY post_id 
       having count(distinct pt.tag_id) =2); 

SQL Fiddle with Demo

+0

謝謝您的回答。 我忘了告訴,tags_id可能超過2在搜索條件... 我已更新帖子。 – jlafforgue 2013-05-02 19:58:12

+0

你救我一命!感謝所有人和Fidlle! 我已經在我的請求之前計算了tag_type包含 – jlafforgue 2013-05-02 20:13:25

+0

@jlafforgue歡迎您!請記住,如果此答案或對您的問題的任何回答有幫助,請考慮通過左側的複選標記接受此答案。參見[接受答案如何工作](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – Taryn 2013-05-02 20:16:34