Click to See Complete Forum and Search --> : Complex SQL help


rayhab
03-09-2009, 07:50 PM
Hi,
I am working in MySQL.

I have a table mytable(id1, ...) and myext(id1, id2)

myext
id1 id2
-------- ---------------
1 1
1 2
1 3
2 1
2 2
2 4
3 4
3 5
3 1
4 5

Now what i want to to select ALL id1 that have an id2 of 1 AND 2.. so from teh table above, it should only return an id1 of 1 and 2. It should also work if i want it to return all id2 of 1 AND 2 AND 3 AND so on.

I am looking for the best solution to this problem.

Any help would be appreciated.

Nedals
03-09-2009, 11:54 PM
SELECT id1 FROM mytable WHERE id2 IN (1,2)

It should also work if....
SELECT id1 FROM mytable WHERE id2 IN (1,2,3,4)

rayhab
03-10-2009, 12:12 AM
SELECT id1 FROM mytable WHERE id2 IN (1,2) would select id1 3 also though...
WHERE IN selects 1 OR 2.. i want ONLY 1 AND 2

Nedals
03-10-2009, 07:22 PM
Now what i want to to select ALL id1 that have an id2 of 1 AND 2...
-and-

...so from teh table above, it should only return an id1 of 1 and 2.

Those are two conflicting requirements. What do you really want?

+-- SELECT id1 FROM mytable WHERE id2 IN (1,2)
|
| +-- SELECT id1 FROM mytable WHERE id1 IN (1,2) AND id2 IN (1,2)
id1 id2 | |
--- ---
1 1 * *
1 2 * *
1 3
2 1 * *
2 2 * *
2 4
3 4
3 5
3 1 *
4 5

rayhab
03-11-2009, 12:58 AM
+-- SELECT id1 FROM mytable WHERE id2 IN (1,2)
|
| +-- SELECT id1 FROM mytable WHERE id1 IN (1,2) AND id2 IN (1,2)
| +-- *** This is what i want.. but won't work with below..
| +-- *** Only A and B should be returned.. you only have 1 and 2 to work with
id1 id2 | |
--- ---
A 1 * *
A 2 * *
A 3
B 1 * *
B 2 * *
B 4
C 4
C 5
C 1 *
D 5