Sql server 选择表1中的记录,其中值来自表2
我这里有两张桌子:Sql server 选择表1中的记录,其中值来自表2,sql-server,join,Sql Server,Join,我这里有两张桌子: table1 id name idfrom idto 1 test 2 3 2 test3 1 9 table2 id branch status 2 a from 1 b from 9 c to 3 d to 如何根据表2中的状态从表2和表1中选择分支 我希望结果如下所示: id name branchfr
table1
id name idfrom idto
1 test 2 3
2 test3 1 9
table2
id branch status
2 a from
1 b from
9 c to
3 d to
如何根据表2中的状态从表2和表1中选择分支
我希望结果如下所示:
id name branchfrom branchto
1 test a d
2 test3 b c
应该执行以下操作(假设您希望在两个表中的id上联接):
这应该适合您:
select t1.id, t1.name, f.branch as branchfrom, f1.branch as branchto
from table1 as t1
join table2 as f
on t1.idfrom = f.id
join table2 as f1
on t1.idto = f1.id
请看这里的演示:我不知道这比其他两个人的建议好还是坏,但是
select
t1.name,
(select
t2.branch
from
table2 t2
where
t1.idfrom = t2.id
) as branchfrom,
(select
t2.branch
from
table2 t2
where
t1.idto = t2.id
) as branchto
from
table1 t1
这里有一个我回答说,这并不意味着我喜欢它
SELECT id, name, bfrom.branch branchfrom, bto.branch branchto
FROM table1 t1
INNER JOIN (SELECT id, branch
FROM table2
WHERE status = 'from') bfrom
ON t1.idfrom = bfrom.id
INNER JOIN (SELECT id, branch
FROM table2
WHERE status = 'to') bto
ON t1.idto = bto.id;
我只使用内部连接作为示例。您必须根据您的要求进行调整(您没有明确指定)。使用以下代码:
CREATE TABLE #table1 (
id int,
name varchar(10),
idfrom int,
idto int
)
CREATE TABLE #table2 (
id int,
branch char,
statuss varchar(10)
)
INSERT INTO #table1
VALUES (1, 'test', 2, 3)
INSERT INTO #table1
VALUES (2, 'test3', 1, 9)
INSERT INTO #table2
VALUES (2, 'a', 'From')
INSERT INTO #table2
VALUES (1, 'b', 'From')
INSERT INTO #table2
VALUES (9, 'c', 'to')
INSERT INTO #table2
VALUES (3, 'd', 'to')
SELECT
a.id,
a.name,
(SELECT
b.branch
FROM #table2 b
WHERE a.idfrom = b.id
AND b.statuss = 'FROM')
AS BranchFrom,
(SELECT
b.branch
FROM #table2 b
WHERE a.idto = b.id
AND b.statuss = 'to')
AS BranchTo
FROM #table1 a
@EKo此查询是否返回任何值?另外,如果可以对列进行直接连接,为什么还要使用子查询呢?谢谢大家提醒,@Nepali Rookie,我修复了连接。我在手机浏览器上写下了答案。当然,老实说,当你有可用的
键时,我不建议在WHERE
子句中使用hardcoded
值。话虽如此,在这种情况下,子查询是完全不必要的。如果表2不包含列status
,我不会在查询中使用它。我们从来不知道OP在表2中使用了什么类型的键。实际上,我们知道在这种情况下键是什么。如果您查看查询,您使用的正是我所说的键。表2中的id
列连接回表1中的idfrom
和idto
列
CREATE TABLE #table1 (
id int,
name varchar(10),
idfrom int,
idto int
)
CREATE TABLE #table2 (
id int,
branch char,
statuss varchar(10)
)
INSERT INTO #table1
VALUES (1, 'test', 2, 3)
INSERT INTO #table1
VALUES (2, 'test3', 1, 9)
INSERT INTO #table2
VALUES (2, 'a', 'From')
INSERT INTO #table2
VALUES (1, 'b', 'From')
INSERT INTO #table2
VALUES (9, 'c', 'to')
INSERT INTO #table2
VALUES (3, 'd', 'to')
SELECT
a.id,
a.name,
(SELECT
b.branch
FROM #table2 b
WHERE a.idfrom = b.id
AND b.statuss = 'FROM')
AS BranchFrom,
(SELECT
b.branch
FROM #table2 b
WHERE a.idto = b.id
AND b.statuss = 'to')
AS BranchTo
FROM #table1 a