繁体   English   中英

SQL-如何选择两个具有关联关系的表之间的所有行,

[英]SQL - how to select all rows between two tables with relations,

首先,我对我的英语不好感到抱歉。

我想选择这两个表中的所有行( CompanyContacts ),但是当两个表之间存在相关数据时,则显示为1行。

表公司:

+---------+-----------+----------+
| cmpy_id | Company   | Cntct_id |
+---------+-----------+----------+
| 1       | Company 1 |   1      |
| 2       | Company 2 |          | 
| 3       | Company 3 |          |
+---------+-----------+----------+

表联系人:

+----------+-----------+
| Cntct_id | Contact   |
+----------+-----------+
| 1        | Contact 1 |
| 2        | Contact 2 |
| 3        | Contact 3 |
+----------+-----------+

结果我需要:

+-----------+------------+
| Contact   |  Company   |
+-----------+------------+
| Contact 1 |  Company 1 |
| Contact 2 |            | 
| Contact 3 |            |
|           |  Company 2 |
|           |  Company 3 |
+-----------+------------+

我怎样才能达到那个结果?

您可以将其表达为左右联接之间的联合:

SELECT
    Contact, Company
FROM
(
    SELECT t1.Contact, t2.Company, 1 AS position
    FROM Contacts t1
    LEFT JOIN Company t2
        ON t1.Cntct_id = t2.Cntct_id
    UNION ALL
    SELECT t1.Contact, t2.Company, 2 AS position
    FROM Contacts t1
    RIGHT JOIN Company t2
        ON t1.Cntct_id = t2.Cntct_id
    WHERE t1.Contact IS NULL
) t
ORDER BY
   position, Contact, Company;

在此处输入图片说明

演示

SELECT Contact,Company 
FROM Contacts contact
LEFT JOIN Company company ON company.Cntct_id=contact.Cntct_id 
UNION 
SELECT Contact,Company 
FROM Contacts contact
RIGHT JOIN Company company ON company.Cntct_id=contact.Cntct_id;

说明:首先,LEFT JOIN将从左侧表(Table:Contacts)中获取所有记录,无论它们在右侧表(Table:Company)中是否匹配,如下所示:

SELECT Contact,Company  
FROM Contacts contact 
LEFT JOIN Company company ON company.Cntct_id=contact.Cntct_id;

Contact     Company
==============================
Contact 1   Company 1
Contact 2   NULL
Contact 3   NULL

然后,第二个RIGHT JOIN将使我们从右表(表:Company)获得所有记录,无论它们在左表(Table:Contacts)中是否匹配,如下所示:

SELECT Contact,Company  
FROM Contacts contact 
RIGHT JOIN Company company ON company.Cntct_id=contact.Cntct_id;

Contact     Company
==============================
Contact 1   Company 1
NULL        Company 2
NULL        Company 3

最后,UNION-“运行这两个查询,然后将结果堆叠在一起”; 一些行将来自第一个查询,而某些则来自第二个查询。

SELECT Contact,Company  
FROM Contacts contact LEFT JOIN Company company ON company.Cntct_id=contact.Cntct_id 
UNION 
SELECT Contact,Company 
FROM Contacts contact RIGHT JOIN Company company ON company.Cntct_id=contact.Cntct_id;

Contact     Company
==============================
Contact 1   Company 1
Contact 2   NULL
Contact 3   NULL
NULL        Company 2
NULL        Company 3

注意:如果使用UNION ALL而不是UNION,它将列出重复项。

Contact     Company
==============================
Contact 1   Company 1
Contact 2   NULL
Contact 3   NULL
Contact 1   Company 1
NULL        Company 2
NULL        Company 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM