4

请参阅下面的 DDL:

CREATE TABLE dbaddress
(aid integer identity not null, link_id int, link_type char, primary key (aid))
CREATE TABLE dbDoorSupervisor
(did integer identity not null, name varchar(30), primary key (did))
CREATE TABLE dbLicensee
(lid integer identity not null, name varchar(30), primary key (lid))

INSERT INTO dbDoorSupervisor (name) values ('Ian')
INSERT INTO dbLicensee (name) values ('Maria')
INSERT INTO dbaddress (link_id, link_type) values (1,'D')
INSERT INTO dbaddress (link_id, link_type) values (1,'L')

我正在尝试根据提供的 Address.AID 获取门禁主管或被许可人的姓名。例如,如果在 WHERE 子句中提供了辅助 1,则从门监督表中返回 Ian,但是如果在 WHERE 子句中提供辅助 2,则从被许可方表中返回 Maria。

我知道您可以在 SELECT 子句中使用 CASE 语句,但是您可以在 FROM 子句中使用它们,即根据提供的 AID 从地址连接到被许可人或从地址连接到门禁管理员吗?

4

3 回答 3

4

您可以像这样在部分中切换left outer join

select
    isnull(d.name, l.name) as name
from dbaddress as a
    left outer join dbDoorSupervisor as d on d.did = a.link_id and a.link_type = 'D'
    left outer join dbLicensee as l on l.lid = a.link_id and a.link_type = 'L'

或者无论如何都加入并在case语句中切换

select
    case a.link_type
        when 'D' then d.name
        when 'L' then l.name
    end as name
from dbaddress as a
    left outer join dbDoorSupervisor as d on d.did = a.link_id
    left outer join dbLicensee as l on l.lid = a.link_id

如果要显示的列不止一列,则可以使用外部应用,这样就不必重复大小写:

select
    c.name, c.address, c.second_name
from dbaddress as a
    left outer join dbDoorSupervisor as d on d.did = a.link_id
    left outer join dbLicensee as l on l.lid = a.link_id
    outer apply (
        select d.name, d.second_name, d.address where a.link_type = 'D' union all
        select l.name, l.second_name, l.address where a.link_type = 'L'
    ) as c
于 2013-10-11T20:22:39.980 回答
2
select a.linkd_id,
case when link_type = 'D' then d.name
    when link_type = 'L' then l.name
end as 'Name'
from dbAddress a
left join dbDoorSupervisor d on d.did = a.link_id
left join dbLicensee l on l.lid = a.link_id
于 2013-10-11T20:21:00.043 回答
0

并非没有动态 SQL,它有自己的一系列问题。

如果您的数据库像这样简单,只有 2 种左右的可能性,一种简单的方法是连接两者并手动处理结果,例如:

select
    a.aid
    ,case a.link_type
        when 'D' then ds.name
        when 'L' then l.name
    end [name]
from
    dbaddress a
left join
    dbDoorSupervisor ds on a.link_type = 'D' and a.link_id = ds.did
left join
    dbLicensee l on a.link_type = 'L' and a.link_id = l.lid
于 2013-10-11T20:19:43.270 回答