![](/img/trans.png)
[英]T-SQL: Select foreign key from one table and find corresponding rows in another
[英]Select rows in a table which aren't in another one with a nullable foreign key
我有以下数据库在Android 3.0平板电脑应用程序中使用它。
我想选择它不在EReportDefect
上的每个缺陷。 如您所见, EReportDefect.defectId
可能为null 。
此选择返回0行。 但是有一些缺陷不在EReportDefect
表上。
SELECT
Defect.defectId,
Defect.description
FROM
Defect
WHERE
qapId = ? AND
defectId NOT IN
(SELECT defectId FROM EReportDefect WHERE eReportId = ?);
我究竟做错了什么?
您可以使用LEFT JOIN
连接列defectID
上的两个表,
SELECT a.*
FROM Defect a
LEFT JOIN EReportDefect b
ON a.defectID = b.defectID
WHERE b.defectID IS NULL
如果a.defectID
上没有匹配项,则b.defectID
将具有NULL
值。
更新1
SELECT a.*
FROM Defect a
LEFT JOIN EReportDefect b
ON a.defectID = b.defectID
WHERE b.defectID IS NULL AND
a.qapID = ?
-- AND b.ReportID = ?
这就是我制作作品的方式:
SELECT
Defect.defectId,
Defect.description
FROM
Defect
WHERE
qapId = ? AND
defectId NOT IN
(SELECT
defectId
FROM
EReportDefect
WHERE eReportId = ? AND defectId IS NOT NULL);
也许我错过了一些东西,但对我来说,似乎你删除“qapId =?AND”和“WHERE eReportId =?” 它应该只返回EReportDefect表中没有条目的结果
SELECT
Defect.defectId,
Defect.description
FROM
Defect
WHERE
defectId NOT IN
(SELECT defectId FROM EReportDefect);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.