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

时间:2017-11-20 11:33:30

标签: mysql

首先,我很抱歉我的英语不好。

我想选择这两个表中的所有行(公司联系人),但是当两个表之间有相关数据时,则显示为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 |
+-----------+------------+

我如何实现这一结果?

2 个答案:

答案 0 :(得分:1)

您可以将此短语称为左右连接之间的联合:

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;

enter image description here

Demo

答案 1 :(得分:1)

char s[] = "12|34|56|78";

for (int i = 0; s[i]; i++) {
    if (s[i] == '|') {
        cout << ", ";
    }
    else {
        cout << s[i];
    }
}

说明: 首先LEFT JOIN将从左表(表:联系人)获取所有记录,无论他们是否在右表(表:公司)中匹配,如下所示:

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;

然后第二个RIGHT JOIN将从右表(表:公司)获取所有记录,无论他们是否在左表(表:联系人)中匹配,如下所示:

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

最后UNION - &#34;运行这两个查询,然后将结果堆叠在一起#34 ;;一些行将来自第一个查询,一些来自第二个查询。

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 ALL而不是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