SELECTING with multiple WHERE conditions on same column

后端 未结 12 926
南旧
南旧 2020-11-22 07:00

Ok, I think I might be overlooking something obvious/simple here... but I need to write a query that returns only records that match multiple criteria on the same column...<

相关标签:
12条回答
  • 2020-11-22 07:49

    Try to use this alternate query:

    SELECT A.CONTACTID 
    FROM (SELECT CONTACTID FROM TESTTBL WHERE FLAG = 'VOLUNTEER')A , 
    (SELECT CONTACTID FROM TESTTBL WHERE FLAG = 'UPLOADED') B WHERE A.CONTACTID = B.CONTACTID;
    
    0 讨论(0)
  • 2020-11-22 07:49
    select purpose.pname,company.cname
    from purpose
    Inner Join company
    on purpose.id=company.id
    where pname='Fever' and cname='ABC' in (
      select mname
      from medication
      where mname like 'A%'
      order by mname
    ); 
    
    0 讨论(0)
  • 2020-11-22 07:53

    can't really see your table, but flag cannot be both 'Volunteer' and 'Uploaded'. If you have multiple values in a column, you can use

    WHERE flag LIKE "%Volunteer%" AND flag LIKE "%UPLOADED%"
    

    not really applicable seeing the formatted table.

    0 讨论(0)
  • 2020-11-22 07:54

    Use this: For example:

    select * from ACCOUNTS_DETAILS
    where ACCOUNT_ID=1001
    union
    select * from ACCOUNTS_DETAILS
    where ACCOUNT_ID=1002
    
    0 讨论(0)
  • 2020-11-22 07:58

    You can either use GROUP BY and HAVING COUNT(*) = _:

    SELECT contact_id
    FROM your_table
    WHERE flag IN ('Volunteer', 'Uploaded', ...)
    GROUP BY contact_id
    HAVING COUNT(*) = 2 -- // must match number in the WHERE flag IN (...) list
    

    (assuming contact_id, flag is unique).

    Or use joins:

    SELECT T1.contact_id
    FROM your_table T1
    JOIN your_table T2 ON T1.contact_id = T2.contact_id AND T2.flag = 'Uploaded'
    -- // more joins if necessary
    WHERE T1.flag = 'Volunteer'
    

    If the list of flags is very long and there are lots of matches the first is probably faster. If the list of flags is short and there are few matches, you will probably find that the second is faster. If performance is a concern try testing both on your data to see which works best.

    0 讨论(0)
  • 2020-11-22 07:59

    Consider using INTERSECT like this:

    SELECT contactid WHERE flag = 'Volunteer' 
    INTERSECT
    SELECT contactid WHERE flag = 'Uploaded'
    

    I think it it the most logistic solution.

    0 讨论(0)
提交回复
热议问题