我需要从我的mysql表中选择一行。
在表中有两行,其中一个值相等。
TABLE
-----
articleId
keywordId
现在我需要选择一篇文章,其关键字ID = 1,以及关键字ID = 12。
关键字的每个链接都有自己的记录。
如果有一篇文章,如何匹配这两个关键字,我该怎么做一个选择查询?
答案 0 :(得分:13)
试试这个:
SELECT *
FROM tablename
WHERE keywordId IN (1, 12)
GROUP BY articleId
HAVING COUNT(*) = 2;
答案 1 :(得分:3)
这称为Relation Division。这是一种方法:
SELECT *
FROM tablename
WHERE articleId IN
(
SELECT articleId
FROM tablename
WHERE KeywordId IN (1, 2)
GROUP BY articleId
HAVING COUNT(KeywordId ) = 2
);;
答案 2 :(得分:1)
SELECT *
FROM `table_name`
WHERE `keywordId` = '1' AND `keywordId` = '12'
答案 3 :(得分:1)
您还可以为每个关键字使用子查询并加入
select k1.articleId from
(
select articleId from TABLE where keywordId = 1
) k1
inner join
(
select articleId from TABLE where keywordId = 12
) k2 on k1.articleId = k2.articleId
根据索引和表大小,这可能比Group By
更有效答案 4 :(得分:1)
select ArticleId from Table where keywordId = 1
Intersect
select ArticleId from Table where KeywordId = 12
答案 5 :(得分:0)
SELECT *
FROM table
WHERE keywordId IN (1, 12);