Selecting rows based on multiple WHERE conditions

一个人想着一个人 提交于 2019-12-08 10:08:53

问题


I want to gather all the details from a table PROD about rows containing particular triplet-sets of values. For example, I want to get all the data on the rows having columns (ID, NBR AND COP_I) with values (23534, 99, 0232) and (3423,5,09384), etc. I tried Version 1, but it only gives me a couple of such rows when I know there needs to be 100 and Version 2 runs into an error. I wasn't able to think of any other way to do this.

Version 1:

SELECT * FROM PROD

WHERE 

ID IN (2534, 3423) 

AND NBR IN (99, 5)

AND COP_I IN (0232, 09384)  

Version 2:

SELECT * FROM PROD

WHERE 

    (ID = '23534',  NBR ='99',  COP_I ='0232'),
AND (ID = '3423',   NBR ='5',   COP_I ='09384')

Update:

I currently get something like:

ID     NBR_IN   COP_I  FLAG  TYPE     DATE 
23534  99       0232   0     CATHAY   15-04-2017

And don't end up getting the (3423, 5, 09384) triplet's row. Basically, only some of the triplet's rows appear in the results and the results turn out to be the same as what I get from Version 1 above.

Thank You


回答1:


I think you should use an OR condition.

SELECT * FROM PROD
WHERE (ID = '23534' AND  NBR ='99' AND COP_I ='0232')
OR (ID = '3423' AND NBR ='5' AND COP_I ='09384')



回答2:


Your second query was going along the right track except that you need to replace the AND with an OR and the ,s with ANDs.

SELECT * 
FROM PROD
WHERE 
    (ID = '23534' AND NBR ='99' AND COP_I = '0232')
OR 
    (ID = '3423' AND  NBR ='5' AND COP_I = '09384')



回答3:


You can specify triplets like this:

SELECT * FROM PROD 
WHERE ( id, nbr, cop_i ) IN ( ('23534','99','0232'), ('3423','5','09384') );



回答4:


You can use a query like the following:

SELECT p.* 
FROM PROD AS p
INNER JOIN (
   SELECT 23534 AS col1, 99 AS col2, 232 AS col3 UNION ALL
   SELECT 3423,          5,          9384
) AS t ON p.ID = t.col1 AND p.NBR = t.col2 AND p.COP_I = t.col3



回答5:


depending on how many pairs of values you may need to do this with, and your RDBMS, you could do something like this:

create table #tempThingy (ID int, NBR int, COP_I int)

insert into #tempThingy (id, nbr, cop_i) 
select 23534, 99, 0232
union all select 3423, 5, 09384

select   *
from prod p
inner join #tempThingy t on p.id = t.id
    and p.nbr = t.nbr
    and p.cop_i = t.cop_i


来源:https://stackoverflow.com/questions/38271715/selecting-rows-based-on-multiple-where-conditions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!