'Select Query by Pair of fields using an in clause
I have a table called players as follows:
First_Id Second_Id Name
1 1 Durant
2 1 Kobe
1 2 Lebron
2 2 Dwight
1 3 Dirk
I wish to write a select statement on this table to retrieve all rows whose first ids and second ids match a bunch of specified first and second ids.
So for example, I wish to select all rows whose first and second ids are as follows: (1,1), (1,2) and (1,3). This would retreive the following 3 rows:
First_Id Second_Id Name
1 1 Durant
1 2 Lebron
1 3 Dirk
Is it possible to write a select query in a manner such as:
SELECT *
FROM PLAYERS
WHERE (First_Id, Second_Id) IN ((1,1), (1,2) and (1,3))?
If there is a way to write the SQL similar to the above I would like to know. Is there a way to specify values for an IN clause that represents multiple rows as illustrated.
I'm using DB2.
Solution 1:[1]
This works on my DB2 (version 9.7 on Linux/Unix/Windows) by using this syntax:
SELECT *
FROM PLAYERS
WHERE (First_Id, Second_Id) IN (VALUES (1,1), (1,2), (1,3))
This syntax won't work on DB2 on the Mainframe (at least in version 9.1) because you can't substitute a sub-select with a VALUES expression. This syntax will work:
SELECT *
FROM PLAYERS
WHERE (First_Id, Second_Id) IN (SELECT 1, 1 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 1, 2 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 1, 3 FROM SYSIBM.SYSDUMMY1)
Solution 2:[2]
Here's a very similar solution in postgresql:
SELECT tmp_table.val1, tmp_table.val2
FROM tmp_table
WHERE (tmp_table.val1, tmp_table.val2) not in (select tmp_table2.val1, tmp_table2.val2 from tmp_table2);
Solution 3:[3]
With compound primary keys, I would concatenate the two ids and match compound strings.
select id1 + id2 as FullKey, *
from players
where FullKey in ('11','12','13')
(If ids are not strings, simply cast them as such.)
Solution 4:[4]
SELECT * FROM <your table> where (<field1>, <field2>, ...) in (SELECT <field1>, <field2>, ... FROM <your table> where <your condition>)
This worked wonder for me.
Solution 5:[5]
This syntax works in MySQL:
SELECT *
FROM PLAYERS
WHERE (First_Id, Second_Id) IN ((1,1), (1,2), (1,3))
Solution 6:[6]
This type of query works in DB2.
SELECT * FROM A
WHERE (C1, C2) IN (SELECT B1, B2 FROM B WHERE B3=1);
Solution 7:[7]
If data is needed in below order:
| First_Id | Second_Id | Name |
|---|---|---|
| 1 | 1 | Durant |
| 1 | 2 | Lebron |
| 1 | 3 | Dirk |
| 2 | 1 | Kobe |
| 2 | 2 | Dwight |
then simple and easy way would be:
select * from players order by First_id, second_id;
"where" clause can be used if any condition is needed on any of the column.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Botz3000 |
| Solution 3 | SQLCurious |
| Solution 4 | Merkurial |
| Solution 5 | MichaelG |
| Solution 6 | Ankit Bajpai |
| Solution 7 |
