您的查询应该是这样的:
SELECT
DISTINCT articles.aid
FROM articles
INNER JOIN tags
ON articles.aid = tags.aid
WHERE tags.tag IN ("green", "pink", "black");
由于两个表有一个共同的属性(即文章ID),您可以使用一个内连接来加入两个表格,并根据两个表格中的其他属性(在本例中为标记名称)过滤结果。
上述查询将为您提供带有绿色,粉红色或黑色标记的文章ID列表。
编辑
对不起,我没有看到你的相关要求。如果您想了解有多少标签每篇文章被发现了,把它变成一个分组的查询,并找到COUNT的标签数量:
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)
谢谢您的回复!这适用于标签。但我也想在文章标题中进行搜索。例如,searchterm是“绿色”,没有标签是“绿色”,但是其中有一个文字标题“绿色”。 (对不起,我的英语不好) – Rob