MySQL选择AND语句

时间:2017-11-14 09:57:42

标签: php mysql

我有一个像这样的MySQL数据库:

Id | Name
1  | term1
1  | term2
1  | term3
2  | term4
2  | term5
2  | term6

我想选择包含term1 AND term3的ID。

或者,例如,term4 AND term5 AND term6。

我该怎么做? 非常感谢任何帮助,谢谢。

3 个答案:

答案 0 :(得分:1)

要获取必须具有作为参数提供的名称的ID,您可以使用以下查询使用某些聚合来满足条件

对于term1& TERM3

select Id
from demo
where Name in ('term1', 'term3')
group by Id
having count(*) = sum(Name in ('term1', 'term3'));

对于term4& term5& term6

select Id
from demo
where Name in ('term4', 'term5','term6')
group by Id
having count(*) = sum(Name in ('term4', 'term5','term6'));

Demo

答案 1 :(得分:0)

以下查询会为您提供所有Id,其中Name是'term1'

SELECT Id from table where Name in ('term1');

获取具有term1或term3

的Id
SELECT Id from table where Name in ('term1', 'term3');

答案 2 :(得分:0)

 SELECT Id, Count(Distinct Name)
 FROM Table
 WHERE Name in ('term1','term3')
 Group By Id 
 HAVING Count(Distinct Name) > 1

我认为这就是你想要的。如果您想要3个术语,请更改“有...”> 2