How do I select missing table rows belonging to Table A from Table B?
table1
id, name, desc
1, Abc, some desc
2, Def, more desc
4, Jkl, another desc
table2
id, table1_id, title
1, 1, My title
2, 1, Another title
3, 3, Yet another title
Table 1 has row with id of 3 "missing". But if you notice, there is one refernece to this missing id in table2. So my question is how do I select all rows of table2 which has references to table1_id(s) which no longer are availabe in table1??
I am not very good at mysql queries and tried something like ... SELECT b.* FROM table2 b INNER JOIN ta开发者_如何学运维ble1 a ON b.table1_id != a.id and some others but could not get the desired result.
Could you throw some idea how this can be achieved? Thanks
SELECT b.*
FROM table2 b
LEFT JOIN table1 a ON b.table1_id = a.id
WHERE a.id is null
Just some minor changes, from INNER to LEFT OUTER, with the condition that a.id is null (no match found in table a).
For deletes, use
DELETE FROM table2
WHERE table1_id not in (select id from table1)
精彩评论