Skip to content
Advertisement

How can I query the list of IDs with conditions on couple of fields?

I have the following two tables:

Table A

ID Code1 Code2
--------------
1 2000  1
2 3000  2
3 1000  3
4 2100  1
5 3500  5

Table B

Code1 Code2
-----------
2100  7
2100  1
3000  2
1000  4

I need to get the IDs from Table A that have values of Code1, Code2 equal to values of Code1,Code2 from table B?

I need to get the following result.

ID 
--
2
4

Advertisement

Answer

You can try this using exists as shown below.

create table TableA (id int, Code1 int, Code2 int)
insert into TableA values
(1, 2000,  1),
(2, 3000,  2),
(3, 1000,  3),
(4, 2100,  1),
(5, 3500,  5)

Create table TableB(Code1 int, Code2 int)
insert into TableB Values
(2100,  7),
(2100,  1),
(3000,  2),
(1000,  4)

Select 
   TableA.Id
from TableA
where exists (Select 1 from TableB where tableA.Code1 = tableB.Code1
and TableA.Code2 = tableB.Code2)

Here is the live db<>fiddle demo. It looks as shown in the below image.

enter image description here

Another way is to use the SQL JOIN and different types of JOINs .

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement