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

时间:2019-06-30 11:07:09

标签: 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        Uploaded    2

所以从这里开始,我想获取ID为1和2的行,而忽略其余的值。但是例如,假设ID为2的行不存在,该语句将不返回任何行。

我尝试了以下语句,但似乎不起作用:

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

3 个答案:

答案 0 :(得分:0)

您应该使用OR

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

    SELECT * FROM docs 
    WHERE id = 1  
    OR  id = 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

答案 1 :(得分:0)

您需要子查询

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

子查询将仅选择计数为2的那些contactid,并且在主查询的情况下将帮助您选择所需的id

答案 2 :(得分:0)

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

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

有多种获取原始行的方法-使用inexistsjoin

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;