2012-05-09 233 views
1

表:taxonomy_term_dataMySQL查詢幫助 - 需要

tid name 
7  desert 
10 indian 

表:taxonomy_index

nid tid 
13  7 
10  7 
10  10 
12  7 
14  10 

我需要一個mysql查詢來獲取其中有 「沙漠」,也是 「印度」 的NID。 這裏的輸出是nid = 10。 有人可以幫助寫入查詢。我只是一個初學者

回答

2
SELECT nid 
FROM taxonomy_index 
JOIN taxonomy_term_data USING (tid) 
WHERE name IN ('desert', 'indian') 
GROUP BY nid 
HAVING COUNT(DISTINCT tid) = 2 

看到它聯機工作:sqlfiddle

+0

此工程.... SELECT NID FROM taxonomy_index JOIN taxonomy_term_data使用(TID) 其中name IN( '沙漠', '印度') GROUP BY NID HAVING COUNT(*)> 1個 – Parthi04

+0

謝謝,我得到了@馬克拜爾斯 – Parthi04

1

你可以通過GROUP BY這個答案和HAVING:

SELECT nid 
FROM taxonomy_index 
WHERE tid IN (7, 10) 
GROUP BY nid 
HAVING COUNT(*) > 1 
+0

這個工程....謝謝。我的搜索條件將使用「Desert&indian」這個名字。如何將這兩個表結合和得到的結果 – Parthi04

+0

這工作。選擇NID FROM taxonomy_index JOIN taxonomy_term_data使用(TID) 其中name IN( '沙漠', '印度') GROUP BY NID HAVING COUNT(*) > 1 – Parthi04

0

假設(nid, tid)組合是唯一的:

SELECT ta.nid 
FROM taxonomy_index AS ta 
    JOIN taxonomy_index AS tb 
    ON tb.nid = ta.nid 
WHERE ta.tid = 7 
    AND tb.tid = 10 
1

你可以用各種SQL書寫風格如下:

1.

SELECT DISTINCT(i.nid) 
FROM taxonomy_index i 
INNER JOIN taxonomy_term_data d 
ON i.tid = d.tid 
AND (d.name = 'desert' 
OR d.name = 'indian') 

2.

SELECT i.nid 
FROM taxonomy_index i 
INNER JOIN taxonomy_term_data d 
ON i.tid = d.tid 
AND (d.name = 'desert' 
OR d.name = 'indian') 
GROUP BY nid 

3.

SELECT i.nid 
FROM taxonomy_index i, taxonomy_term_data d 
WHERE i.tid = d.tid 
AND d.name IN ('desert', 'indian') 
GROUP BY nid 

4.

SELECT DISTINCT(nid) 
FROM taxonomy_index 
WHERE (tid = 7 
OR tid = 12) 
+0

http://stackoverflow.com/q/10511532/1257426 – Parthi04