2012-05-09 237 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