您的查詢應該是這樣的:
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