FK列可能为null或其他值(不是父表中的PK)。
你可以试试这个
Select * from child_table where FK not in (select PK from parent_table)
Try this
SELECT ChildTable.ParentID
FROM ChildTable
WHERE NOT EXISTS (
SELECT 1 FROM ParentTable
WHERE ChildTable.ParentID = ParentTable.ParentID
)
You can use LEFT JOIN
to get the expected result.
Please refer the following working example with sample data:
DECLARE LOCAL TEMPORARY TABLE ParentTable TABLE (Id INT IDENTITY(1,1) , [Name] VARCHAR (100));
DECLARE LOCAL TEMPORARY TABLE ChildTable TABLE (Id INT IDENTITY(1,1), ParentId INT NULL, [Value] VARCHAR (50));
INSERT INTO ParentTable VALUES ('Name 001'), ('Name 002'), ('Name 003');
INSERT INTO ChildTable VALUES (1, 'Val 01'), (2, 'Val 02'), (NULL, 'Val 03'), (4, 'Val 04');
SELECT C.*
FROM ChildTable C
LEFT JOIN ParentTable P ON P.Id = C.ParentId
WHERE P.Id IS NULL;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.