我需要从我的 mysql 表中选择一行。
在表中有两行具有一个相等的值。
TABLE
-----
articleId
keywordId
现在我需要选择一篇文章,它的关键字 Id = 1,以及关键字 Id = 12。
每个指向关键字的链接都有自己的记录。
我怎样才能做一个选择查询来知道,如果有一篇文章,匹配这两个关键字?
尝试这个:
SELECT *
FROM tablename
WHERE keywordId IN (1, 12)
GROUP BY articleId
HAVING COUNT(*) = 2;
这称为关系划分。这是一种方法:
SELECT *
FROM tablename
WHERE articleId IN
(
SELECT articleId
FROM tablename
WHERE KeywordId IN (1, 2)
GROUP BY articleId
HAVING COUNT(KeywordId ) = 2
);;
您还可以为每个关键字使用子查询并加入它们
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 更有效
SELECT *
FROM `table_name`
WHERE `keywordId` = '1' AND `keywordId` = '12'
SELECT *
FROM table
WHERE keywordId IN (1, 12);
select ArticleId from Table where keywordId = 1
Intersect
select ArticleId from Table where KeywordId = 12