Subject Re: [firebird-support] get data from table based on criteria from another table
Author Svein Erling Tysvær
>I have two tables, TABLE_A and TABLE_B
>
>TABLE_A:
>------
>ID: INT
>DATA_A: INT
>
>TABLE_A data:
>(ID, DATA_A)
>1, 11
>2, 12
>3, 13
>4, 14
>9, 19
>
>TABLE_B:
>------
>ID: INT
>DATA_B: INT
>
>TABLE_B data:
>(ID, DATA_B)
>1, 100
>2, 200
>3, 200
>5, 100
>7, 300
>9, 100
>
>I want to do the following: get all records from TABLE_A, for which ID exists in TABLE_B and DATA_B for that ID equals 100. Or in other words:
>(1).from tableB, get all ID's for which DATA_B = 100 (here - 1,5,9), and then
>(2).get all the records from TABLE_A containing an ID from(1)
>In the above case, the desired result would be
>1, 11
>9, 19
>
>Hope I explained it well.
>Thanks for any suggestions.

Welcome to SQL, Peter! You have several options, the simplest one is:

SELECT A.*
FROM TABLE_A A
JOIN TABLE_B B ON A.ID = B.ID
WHERE B.DATA_B = 100

This will give duplicates in case TABLE_B contains more than one row with the same combination of ID and DATA_B. If so, you may simply add DISTINCT:

SELECT DISTINCT A.*
FROM TABLE_A A
JOIN TABLE_B B ON A.ID = B.ID
WHERE B.DATA_B = 100

unless you want potential duplicates of A to show on several rows. A good solution that fixes this is:

SELECT *
FROM TABLE_A A
WHERE EXISTS(SELECT * FROM TABLE_B B
WHERE A.ID = B.ID
AND B.DATA_B = 100)

All of these three options are simple SQL that normally would get you what you want in no time. If you have many millions of rows in TABLE_A and only a handful in TABLE_B with DATA_B = 100, then the last statement will be noticably slower, but in normal cases where ID is either a primary key or have an index, all three statements will execute sufficiently fast.

HTH,
Set