MySQL MYSQL选择一列的两个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14196134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:05:37  来源:igfitidea点击:

MYSQL Select on two values one column

mysqlsqlselectgroup-by

提问by Tim Hanssen

I need to select a row from my mysql table.

我需要从我的 mysql 表中选择一行。

In the table there are two rows with one equal value.

在表中有两行具有一个相等的值。

TABLE
-----
articleId
keywordId

Now I need to select an article, that has keyword Id = 1, as well as keyword Id = 12.

现在我需要选择一篇文章,其关键字 Id = 1,以及关键字 Id = 12。

Every link to a keyword has its own record.

每个指向关键字的链接都有自己的记录。

How can I do one select query to know, if there is an article, that matches the two keywords?

我怎样才能做一个选择查询来知道,如果有一篇文章,匹配这两个关键字?

回答by Saharsh Shah

Try this:

尝试这个:

SELECT *  
FROM tablename 
WHERE keywordId IN (1, 12) 
GROUP BY articleId 
HAVING COUNT(*) = 2; 

Check the SQL FIDDLE DEMO

检查SQL FIDDLE 演示

回答by Mahmoud Gamal

This is called Relation Division. Here is one way to do so:

这称为关系部门。这是一种方法:

SELECT * 
FROM tablename 
WHERE articleId IN
(
   SELECT articleId
   FROM tablename
   WHERE KeywordId IN (1, 2) 
   GROUP BY articleId
   HAVING COUNT(KeywordId ) = 2
);;

回答by Subhra Sekhar Mukhopadhyay

SELECT * 
FROM `table_name` 
WHERE `keywordId` = '1' AND `keywordId` = '12' 

回答by Rhumborl

You can also use subqueries for each keyword and join them

您还可以为每个关键字使用子查询并加入它们

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

Depending on indexes and table size this can be more efficient than Group By

根据索引和表大小,这可能比 Group By 更有效

回答by Pratik

select ArticleId from Table where keywordId = 1
Intersect
select ArticleId from Table where KeywordId = 12

回答by justMe

SELECT * 
FROM table 
WHERE keywordId IN (1, 12);