tags:

views:

34

answers:

3

Hi Everyone,

I want to be able to loop over a list and return a single row where all the list elements have matched.

e.g.

lest say my list of id's is 1,2,3 I want to write an SQL statment that will do the following (without breaking).

SELECT id1 FROM TBL WHERE 0=0 AND id2 = 1 AND id2 = 2 AND id2 = 3

Is this possible?

Thanks in advance

+2  A: 

AND here makes no sense. You probably want to use OR: id2 = 1 OR id2 = 2 OR id2 = 3 or even better IN:

SELECT id1 FROM TBL WHERE id2 IN (1,2,3)
Mark Byers
That would be `SELECT id1 FROM TBL WHERE 0=0 AND id2 = 1 OR id2 = 2 OR id2 = 3`
James Curran
@James Curran: The 0=0 is not necessary.
Mark Byers
+1 This is an equally viable guess!
Martin Smith
The point I was making was that he specifically wanted "AND". You changed it to "OR".
James Curran
@James Curran: There is obviously an error in the question. The only question is what the error is. To be honest I think Martin Smith's guess is better than mine, but only the OP knows what he was thinking when he wrote the question.
Mark Byers
Ignore his SQL and read the OP's text. He clearly wants an "AND" of some form. (I was thinking of a second table with a many-to-one)
James Curran
@James Curran: What do you think the question means? Perhaps you can edit the question to make it clear? I don't really understand what he means by "list" and "looping" in an SQL context and he hasn't replied to my questions. :(
Mark Byers
+3  A: 

Do you mean that you want all id1 records for which there is a matching id2=1 and a matching id2=2 and a matching id2=3?

WITH tbl As
(
SELECT 1 AS id1, 1 AS id2 UNION ALL
SELECT 1 AS id1, 2 AS id2 UNION ALL
SELECT 1 AS id1, 3 AS id2 UNION ALL
SELECT 1 AS id1, 4 AS id2 UNION ALL
SELECT 2 AS id1, 1 AS id2 UNION ALL
SELECT 2 AS id1, 2 AS id2 UNION ALL
SELECT 3 AS id1, 1 AS id2 UNION ALL
SELECT 3 AS id1, 2 AS id2 UNION ALL
SELECT 3 AS id1, 3 AS id2
)
SELECT id1 
FROM tbl 
WHERE id2 IN (1,2,3)
GROUP BY id1
HAVING COUNT(DISTINCT id2) = 3

Returns

id1
-----------
1
3

Is that what you need?

Martin Smith
+1 This is a good guess as to what the OP might mean.
Mark Byers
Hey guys, THank for your quick response.Yeah, so there would have to be three rows. Which would look a little like thisID1 / ID2 1 / 1 1 / 2 1 / 3 Im trying to get the result to eq 1 (the value of id1)
James
@James - See my edit. Is that doing what you need?
Martin Smith
yeah, thats what i need. I'll try this out and let you know. Thanks for you help
James
not only does it work, But I also understand what is going on. Thanks
James
+1  A: 

A third guess, based on the title of the question - if the list of values is in a second table, the query can be written to select values from the first table based on a join to the second table - like so:

SELECT id1 FROM TBL T1
join TBL2 T2 on T1.id2 = T2.id

Of course, in this example TBL2 would have to have only the values 1, 2 and 3 in the id column.

Mark Bannister