Mysql SQL使用筛选器选择行

Mysql SQL使用筛选器选择行,mysql,sql,Mysql,Sql,我有下表: +----+----------+ | id | feature | +----+----------+ | 1 | 10 | | 1 | 20 | | 2 | 20 | | 3 | 40 | | 4 | 50 | | 5 | 60 | +----+----------+ 我想要同时具有10和20两个特征的id。所以,不仅仅是10或20的结果,我还想得到同时有10和20的id的结果 最简单的方法是

我有下表:

+----+----------+
| id | feature  |
+----+----------+
| 1  |   10     |
| 1  |   20     |
| 2  |   20     |
| 3  |   40     |
| 4  |   50     |
| 5  |   60     |
+----+----------+

我想要同时具有10和20两个特征的id。所以,不仅仅是10或20的结果,我还想得到同时有10和20的id的结果

最简单的方法是按id分组并使用:


最简单的方法是按id分组并使用:


选择具有功能10和功能20的id的另一种方法您可以这样做

select id
from table1
group by id
having sum(feature = 10)
and sum(feature = 20)

选择具有功能10和功能20的id的另一种方法您可以这样做

select id
from table1
group by id
having sum(feature = 10)
and sum(feature = 20)

还有一个办法

SELECT ID,
stuff(
(
    select ','+ convert(varchar,feature) from table where Id = t.Id for XML path('')
),1,1,'') [comma_sep_feature]
FROM [table] t 
group by id
您可以在temp中插入此值,并添加where子句comma_sep_feature='10,20',如下所示

SELECT ID,
        stuff(
        (
            select ','+ convert(varchar,feature) from yourtable where Id = t.Id for XML path('')
        ),1,1,'') [comma_sep_feature]
        into #tem
        FROM [yourtable] t 
        group by id

    select * from #tem where comma_sep_feature = '10,20'

    drop table #tem

还有一个办法

SELECT ID,
stuff(
(
    select ','+ convert(varchar,feature) from table where Id = t.Id for XML path('')
),1,1,'') [comma_sep_feature]
FROM [table] t 
group by id
您可以在temp中插入此值,并添加where子句comma_sep_feature='10,20',如下所示

SELECT ID,
        stuff(
        (
            select ','+ convert(varchar,feature) from yourtable where Id = t.Id for XML path('')
        ),1,1,'') [comma_sep_feature]
        into #tem
        FROM [yourtable] t 
        group by id

    select * from #tem where comma_sep_feature = '10,20'

    drop table #tem

在whare之后使用and子句。whare之后使用and子句。6 10 | 6 10是什么?这将是一个非常好的问题,你需要使用的总和看到答案Khalid@splash58op只提供了样本数据,没有提供表定义,id上应该有唯一的复合索引,feature@AbhikChakraborty你也可以加上HAVING COUNTdistinct feature=2,我想你只是忘记了:正确的distinct应该做这项工作,但是HAVING sum看起来很性感:那么6 10 | 6 10呢?这将是一个非常好的问题,你需要使用的总和看到答案Khalid@splash58op只提供了样本数据,没有提供表定义,id上应该有唯一的复合索引,feature@AbhikChakraborty你也可以添加HAVING COUNTdistinct feature=2我想你只是忘记了:正确的distinct应该做这项工作,但是HAVING sum看起来很性感:@OP检查这个答案它解决了你在我的答案中问我的问题@OP检查这个答案它解决了你在我的答案中问我的问题!