1

表:taxonomy_term_data

tid   name
7     desert
10    indian

表:taxonomy_index

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

我需要一个 mysql 查询来获取具有“沙漠”和“印度”的 nid。这里的输出是nid = 10。有人可以帮助编写查询。我只是一个初学者

4

4 回答 4

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

于 2012-05-09T05:38:09.367 回答
1

您可以通过 GROUP BY 和 HAVING 获得此答案:

SELECT nid
FROM taxonomy_index
WHERE tid IN (7, 10)
GROUP BY nid
HAVING COUNT(*) > 1
于 2012-05-09T05:39:19.750 回答
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)
于 2012-05-09T07:22:08.357 回答
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
于 2012-05-09T07:03:10.587 回答