SQL Server加入其他表

时间:2018-02-06 15:32:49

标签: sql sql-server inner-join

+-------------------+   +-------------------+   +---------------------+
|      Service      |   |       Asset       |   |     AssetService    |
+-------------------+   +-------------------+   +---------------------+
| Id   |    Name    |   | Id   |    Name    |   | AssetId | ServiceId |
|-------------------|   |-------------------|   |---------------------|
| 1    |  Service 1 |   | 1    |   Asset 1  |   |     1   |     1     |
| 2    |  Service 2 |   | 2    |   Asset 2  |   |     1   |     2     |
| 3    |  Service 3 |   | 3    |   Asset 3  |   |     2   |     2     |
+-------------------+   +-------------------+   |     2   |     3     |
                                                +---------------------+

所以我有这些表。我希望得到Services AssetService AssetId = 1 +-------------------+ | Service | | Id | Name | +-------------------+ | 3 | Service 3 | +-------------------+ 像这样:

inner join Asset a on a.Id != as.AssetId

只有内/左/右连接可以实现吗?因为我已经尝试过内部联接的不同组合,但它不起作用,就像这个cars[]一样。我事件尝试了左右加入。

有人能帮助我吗?

感谢。

3 个答案:

答案 0 :(得分:3)

我能想到的最简单:

select * from Service
where Id not in (
    select ServiceId
    from AssetService 
    where AssetId = 1);

SQLFiddle link

我认为使用inner join是不可能的,因为这只会检索符合某些条件的记录,并且您正在查找匹配的记录。

然而,可以使用left join进行此操作,正如Ctznkane525在his answer中所示。

修改

在评论中指出jarlh,当子查询中存在空值时,not in可能会导致surprising results。所以,这是not exists版本:

select Id, Name
from Service s
where not exists (
    select *
    from AssetService a
    where AssetId = 1
    and ServiceId = s.Id);

SQLFiddle link

答案 1 :(得分:3)

您可以使用智能左连接仅从左表(服务)返回不匹配的行

SELECT S.Id, S.Name FROM [Service] S
LEFT JOIN ServiceAsset SA
ON S.Id = SA.ServiceId
WHERE SA.ServiceId IS NULL

enter image description here

注意: INNER JOIN返回匹配的行,而您希望不匹配的行然后使用LEFT JOIN

答案 2 :(得分:2)

试试这个:

select * from Service where Id not in (
    select ServiceId from AssetService where AssetId = 1 
    -- we have to filter out NULLs, in case of NULL values query result will be empty
    and ServiceId not null
)

它不需要任何join

以下是join的解决方案:

select Id, Name from Service
except
select S.Id, S.Name from Service S join AssetService [AS] on S.Id = [AS].ServiceId
where [AS].AssetId = 1