SQL Query自联接来自两个表

时间:2017-02-13 08:09:15

标签: sql inner-join

我坚持以下问题。 有两个表:

银行

bank_id [PK] | name
---------------------
 1            Bank_1
 2            Bank_2
 3            Bank_3
 4            Department_1
 5            Department_2
 6            Department_3

关系

id [PK] | parent_id | filial_id
--------------------------------   
 1         1            5
 2         2            4
 3         2            6

需要选择所有银行部门对。 还应选择没有部门的银行。

我写了以下查询:

SELECT A.name AS 'Bank', B.name  AS 'Department'
FROM banks A,
     banks B 
        JOIN relations ON B.bank_id=relations.filial_id
                      AND A.bank_id = relations.parent_id;

但它只显示有部门的银行。我应该如何将查询更改为输出字符串Bank_3,而该字符串没有部门?

4 个答案:

答案 0 :(得分:4)

我认为您的表格应如下所示

  1. 银行表格仅包含 bank_id,银行名称 bank_id 将成为主键。
  2. 部门将有单独的表格,其中包括 bank_id,dept_id,dept_name
  3. departments表中的
  4. bank_id 将是来自银行
  5. 的外键
  6. 部门ID 将成为部门表中的主键
  7. 您的银行表格将按以下方式划分。

        bank_id  bank_name
        1            Bank_1
        2            Bank_2
        3            Bank_3
    
        bank_id dept_id dept_name
           1     4            Department_1
           2     5            Department_2
           2     6            Department_3
    

    然后,您只需使用左连接即可获得所需格式的数据。

    目前,您的银行表中没有银行和部门的识别栏。

答案 1 :(得分:1)

你可以用联盟

SELECT A.name AS 'Bank', B.name  AS 'Department' 
FROM  relations AS R 
INNER JOIN banks AS A ON A.bank_id = R.parent_id
INNER  JOIN banks AS B ON  B.bank_id=R.filial_id ;

UNION 

select name, null
from banks where bank_id not in (select parent_id from relation)

答案 2 :(得分:1)

试试这个:

SELECT A.name AS 'Bank', B.name  AS 'Department' 
FROM (SELECT * FROM banks WHERE NOT EXISTS(SELECT TOP 1 1 FROM Relations WHERE filial_id = bank_id)) A
LEFT OUTER JOIN Relations r 
INNER JOIN banks B ON B.bank_id= r.filial_id ON   A.bank_id = r.parent_id 

输出:

Bank                 Department
-------------------- --------------------
Bank_1               Department_2
Bank_2               Department_1
Bank_2               Department_3
Bank_3               NULL

答案 3 :(得分:0)

部门都是relations.filial_id中存在的“银行”。银行都是没有的“银行”。使用外部联接来获取银行的部门,以便使银行没有部门。

select b.name as bank_name, d.name as department_name 
from (select * from banks where bank_id not in (select filial_id from relations) b
left join relations r on r.parent_id = b.bank_id
left join banks d on d.bank_id = r.filial_id