SQL Server 2008列表项不在表中

时间:2012-11-27 07:12:58

标签: sql sql-server sql-server-2008

一个简单的查询,应查看systemSoftware表和软件表,并仅显示不在softwareId表中的systemSoftware

到目前为止,这是我的查询...

SELECT s.softwareId AS 'Software ID',
    s.softwareDescription AS 'Software Description',
    sv.vendorName AS 'Vendor Name',
    c.cityName AS 'City Name'
FROM software AS s
JOIN systemSoftware AS ss
ON s.softwareId = ss.softwareId
JOIN softwareVendor AS sv
ON s.vendorId = sv.vendorId
JOIN city AS c
ON sv.zipCode = c.zipCode
WHERE s.softwareId NOT IN (ss.softwareId)
ORDER BY s.softwareId
GO

当我删除NOT时,它会显示softwareId中的所有systemSoftware行。

问题是我想要相反。那些不在systemSoftware中的人。

1 个答案:

答案 0 :(得分:2)

您需要左外连接:

SELECT ss.softwareId AS 'Software ID',
    s.softwareDescription AS 'Software Description',
    sv.vendorName AS 'Vendor Name',
    c.cityName AS 'City Name'
FROM software AS s
left outer JOIN systemSoftware AS ss
ON s.softwareId = ss.softwareId
left outer JOIN softwareVendor AS sv
ON s.vendorId = sv.vendorId
left outer JOIN city AS c
ON sv.zipCode = c.zipCode
WHERE ss.softwareId is NULL
ORDER BY s.softwareId

我也更改了ORDER BY,因为按照不存在的列排序是没有意义的。