0

我正在与联接和内部联接作斗争。

我有 2 个如下所示的表:

用户

-----------------------------------------
ID | fname | lname | div_1_id | div_2_id
-----------------------------------------
1    paul    smith     1         2
2    john    lip       2        null
3    kim     long      1         4

部门

------------------
ID | name
------------------
1    estate
2    litigation
3    property
4    civil

期望的结果(sql查询)

--------------------------------------------------
user.ID | fname | lname | div_1_name | div_2_name
--------------------------------------------------
  1        paul    smith     estate       litigation
  2        john    lip       litigation   
  3        kim     long      estate       civil

我想从一个类似于上面的 MS sql 查询创建一个新表。

4

3 回答 3

1

用于LEFT JOIN此:

SELECT u.ID, u.fname, u.lname
      , d1.name as div_1_name
      , d2.name as div_2_name 
FROM USERS u 
LEFT JOIN DIVISIONS d1 ON u.div_1_id = d1.ID 
LEFT JOIN DIVISIONS d2 ON u.div_2_id = d2.ID

看到这个 SQLFiddle

于 2013-04-19T10:43:41.280 回答
1

尝试使用子查询:

select a.ID, a.fname, a.lname,
    (select name from DIVISIONS b where b.id=a.div_1_id) div_1_name,
    (select name from DIVISIONS b where b.id=a.div_2_id) div_2_name
from 
USERS a
于 2013-04-19T10:48:53.613 回答
0

利用INNER JOIN

SELECT Users.ID, Users.fname, Users.lname, Divisions.name,Div.name
FROM Users INNER JOIN Divisions ON Users.div_id_1 = Divisions.ID
INNER JOIN Divisions Div ON Users.div_id_1 = Div.ID -- Second join with Divisions Table with Alias.
于 2013-04-19T10:42:37.490 回答