您的查询应如下所示:
SELECT
DISTINCT articles.aid
FROM articles
INNER JOIN tags
ON articles.aid = tags.aid
WHERE tags.tag IN ("green", "pink", "black");
由于两个表都有一个共同的属性(即文章 ID),因此您可以使用 INNER JOIN 来连接两个表,并根据两个表中的其他属性(在本例中为标签名称)过滤结果。
上面的查询将为您提供带有任何绿色、粉色或黑色标签的文章 ID 列表。
编辑
抱歉,我没有看到您对相关性的要求。如果您想找出在每篇文章中找到了多少标签,请将其转换为 GROUPed 查询,并计算找到的标签数量:
SELECT
articles.aid,
articles.headline,
COUNT(tags.tid)
FROM articles
INNER JOIN tags
ON articles.aid = tags.aid
WHERE tags.tag IN ("green", "pink", "black")
GROUP BY articles.aid;
试试这个场景...
首先,设置数据库:
mysql> CREATE TABLE articles (aid integer auto_increment, headline varchar(32), key(aid));
Query OK, 0 rows affected (0.13 sec)
mysql> CREATE TABLE tags (tid integer auto_increment, aid integer, tag VARCHAR(16), key(tid));
Query OK, 0 rows affected (0.09 sec)
mysql> INSERT INTO articles (headline) values ("This is a green Article"), ("This is another Test");
Query OK, 2 rows affected (0.05 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM articles;
+-----+-------------------------+
| aid | headline |
+-----+-------------------------+
| 1 | This is a green Article |
| 2 | This is another Test |
+-----+-------------------------+
2 rows in set (0.00 sec)
mysql> INSERT INTO tags (aid, tag) VALUES (1, "blue"), (1, "yellow"), (2, "blue"), (2, "yellow"), (2, "pink"), (2, "black");
Query OK, 6 rows affected (0.04 sec)
Records: 6 Duplicates: 0 Warnings: 0
然后运行一些查询:
mysql> SELECT articles.aid, articles.headline, COUNT(tags.tid) FROM articles INNER JOIN tags ON articles.aid = tags.aid WHERE tags.tag IN ("green", "pink", "black") GROUP BY articles.aid;
+-----+----------------------+-----------------+
| aid | headline | COUNT(tags.tid) |
+-----+----------------------+-----------------+
| 2 | This is another Test | 2 |
+-----+----------------------+-----------------+
1 row in set (0.00 sec)
mysql> SELECT articles.aid, articles.headline, COUNT(tags.tid) FROM articles INNER JOIN tags ON articles.aid = tags.aid WHERE tags.tag IN ("green", "pink", "black", "yellow") GROUP BY articles.aid;
+-----+-------------------------+-----------------+
| aid | headline | COUNT(tags.tid) |
+-----+-------------------------+-----------------+
| 1 | This is a green Article | 1 |
| 2 | This is another Test | 3 |
+-----+-------------------------+-----------------+
2 rows in set (0.00 sec)