从table1中选择记录,其中table2的值

时间:2015-05-29 00:14:29

标签: 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

如何根据table2中的状态从table2和table1中选择分支?

我希望结果看起来像这样:

id   name     branchfrom   branchto 
 1   test     a            d
 2   test3    b            c

5 个答案:

答案 0 :(得分:0)

以下内容应该做(假设您想要在两个表中加入id):

select t1.id, t1.name, f.branch as branchfrom, t.branch as branchto
from table1 as t1
join table2 as f
  on f.id = t1.id
  and f.status = 'from'
join table2 as t
  on t.id = t1.id
  and t.status = 'to'

答案 1 :(得分:0)

这应该适合你:

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

请参阅此处了解演示:SQL Fiddle Demo

答案 2 :(得分:0)

我不知道这比其他两个人建议的更好还是更差

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

这是fiddle

答案 3 :(得分:0)

我回答它并不意味着我喜欢它。

            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;

我只使用INNER JOIN作为样本。您必须根据您的要求进行调整(您没有明确说明)。

答案 4 :(得分:0)

使用此代码:

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