Mysql 我想为同一列获取多个值的记录

Mysql 我想为同一列获取多个值的记录,mysql,sql,Mysql,Sql,我试图根据自己的两个值从数据库中获取值,这些值必须与数据库的id匹配 id contactid flag flag_type ----------------------------------- 1 99 Volunteer 1 2 99 Uploaded 2 3 100 Via Import 3 4 100 Volunteer 1 5 100

我试图根据自己的两个值从数据库中获取值,这些值必须与数据库的id匹配

id   contactid  flag        flag_type 
-----------------------------------
1    99         Volunteer   1 
2    99         Uploaded    2 
3    100        Via Import  3 
4    100        Volunteer   1  
5    100        Uploaded    2
因此,我希望从这里获得id为1和2的行,并忽略其余的值。但假设id为2的行不存在,则该语句不会返回任何行

我尝试过以下说法,但似乎不起作用:

SELECT * FROM docs WHERE id IN (1) AND id IN (2);
你应该使用或

    SELECT * FROM docs 
    WHERE id IN (1) OR  id IN (2);

或者如果您需要id为1,2的contactid记录,则

    select * from docs 
    inner join (
        select  contactid 
        from docs 
        where id IN (1, 2) 
        having count(distinct id ) = 2
    ) t on t.contactid = docs.contactid
您需要子查询

select id from table_name where contactid in (
select contactid
from table_nae
group by contactid
having count(*)=2
)

子查询将仅选择计数为2的联系人id,在主查询的情况下,将帮助选择所需的id

如果您希望联系人正好具有这些标志,您可以执行以下操作:

select contactid
from t
group by contactid
having sum(flag = 1) > 0 and         -- has 1
       sum(flag = 2) > 0 and         -- has 2
       sum(flag not in (1, 2)) = 0;  -- has nothing else
有多种方法可以获取原始行-使用in、exists或join:


使用逗号分隔的ID值作为SELECT*从ID位于1,2的文档尝试输入运算符@BarbarosÖzhan我需要两个值都存在,而不仅仅是一个值,因此如果一个值不存在,则语句返回Nothing我需要两个值都存在而不仅仅是一个值,因此如果一个值不存在,则语句返回Nothingnothing@JordanPattinson如果id=2的contactid等于98..怎么办。。?
select contactid
from t
group by contactid
having sum(flag = 1) > 0 and         -- has 1
       sum(flag = 2) > 0 and         -- has 2
       sum(flag not in (1, 2)) = 0;  -- has nothing else
select t.*
from t join
     (select contactid
      from t
      group by contactid
      having sum(flag = 1) > 0 and         -- has 1
             sum(flag = 2) > 0 and         -- has 2
             sum(flag not in (1, 2)) = 0   -- has nothing else
     ) tt
     on t.contactid = tt.contactid;