开发者

How to retrieve all of the records which dont have any reference in another table?

开发者 https://www.devze.com 2022-12-13 05:51 出处:网络
TableA id, name 1, abc 2, cde 3, def TableB id, TableA_id, topic 1, 1, blah 2, 1, blah again 3, 2, abcdef I want 开发者_JS百科to select all of those records from TableA which dont have any refe
TableA 
id, name
1, abc
2, cde
3, def


TableB
id, TableA_id, topic
1, 1, blah 
2, 1, blah again
3, 2, abcdef 

I want 开发者_JS百科to select all of those records from TableA which dont have any references in TableB. How do I do it in Mysql?

Thanks a lot.


You can use LEFT JOIN and select these records which don't have matching record in B.

SELECT
  TableA.*
FROM
  TableA
  LEFT JOIN
    TableB 
  ON
    TableB.TableA_id = TableA.id
WHERE
  TableB.id IS NULL


SELECT TableA.*
FROM TableA
LEFT JOIN TableB ON (TableA.id = TableB.TableA_id)
WHERE TableB.id IS NULL


Select a.*
From TableA a
Left Outer Join TableB b on b.TableA_id=a.id
Where b.id is NULL


SELECT * FROM TableA WHERE id NOT IN (SELECT TableA_id FROM TableB)

0

精彩评论

暂无评论...
验证码 换一张
取 消