0

Consider that I have two tables.

One is "Table1" as shown below.

enter image description here

One more table is "Table2" as shown below.

enter image description here

Now here what I need is, I need all the records from Table1 those ID's are not in Table2's Reference column.

Please guide me how to do this.

Thanks in advance.

4

1 に答える 1

1

How to do it with your current schema (impossible to use indexes):

SELECT Table1.*
FROM Table1
WHERE NOT EXISTS
(
    SELECT 1
    FROM Table2
    WHERE CONCAT(',', Table2.Reference, ',') LIKE CONCAT('%,', Table1.ID, ',%')
)

How this works is by completely wrapping every value in the Reference column with commas. You will end up with ,2,3, and ,7,8,9, for your sample data. Then you can safely search for ,<Table1.ID>, within that string.


How to really do it:

Normalize your database, and get rid of those ugly, useless comma-separated lists.

Fix your table2 to be:

 SlNo | Reference
------+-----------
    1 |        2
    1 |        3
    2 |        7
    2 |        8
    2 |        9

and add a table2Names as:

 SlNo | Name
------+---------
    1 | Test
    2 | Test 2

Then you can simply do:

SELECT Table1.*
FROM Table1
WHERE NOT EXISTS(SELECT 1 FROM Table2 WHERE Table2.Reference = Table1.ID)
于 2013-02-01T04:34:55.503 に答える