如何在此表的左连接后使用左外连接?

时间:2016-07-20 06:33:01

标签: mysql sql-server join

我想加入4个表,以便在其中获取必要的数据。

表A.

id | name | deleted | amount | due_date   | status
1  | a    | 0       | 10     | 2016-07-18 | Unpaid
2  | b    | 0       | 20     | 2016-07-19 | Unpaid
3  | c    | 0       | 15     | 2016-07-18 | Unpaid

表B

id | name   | due_date   | status
1  | a      |            | Unpaid
2  | b      |            | Unpaid
3  | c      |            | Unpaid
4  | d      | 2016-07-19 | Unpaid

表C

id | table_d_id | table_a_id
1  | 1          | 1
2  | 2          | 2
3  | 3          | 3

表D

id | 
1
2
3

我想在这里做的是使用due_date和非付费状态检索表B中的数据,并且在表A中找不到它。

我当前的查询:

SELECT  A.*, B.*, C.*, D.*  
FROM A  
LEFT OUTER JOIN B ON B.name= A.name 
INNER JOIN C ON A.id = C.id  
INNER JOIN D ON C.id = D.id  
WHERE A.deleted=0 AND ((B.due_date < "2016-07-20" AND B.status = "Unpaid") OR (A.due_date < "2016-07-20" AND A.status = "Unpaid")) 
GROUP BY D.id

这个查询当前的作用是它只获取表中的数据,除了表B中的id 4,我还希望检索它,因为它具有未付状态。

3 个答案:

答案 0 :(得分:1)

您应该使用左连接(在您的示例中,b.column是名称而不是数字..)

SELECT  A.*, B.*, C.*, D.*  
FROM B  
LEFT JOIN A_cstm ON A.id = A_cstm.id_c  
LEFT  JOIN A ON B.name = A.name 
INNER JOIN C ON A.id = C.id  
INNER JOIN D ON C.id = D.id  
WHERE A.deleted=0 AND ((B.due_date < "2016-07-20" AND B.status = "Unpaid") OR (A.due_date < "2016-07-20" AND A.status = "Unpaid")) 
GROUP BY D.id

表格A_cstm未在您的模型中描述(为清晰起见,我已移除了..)  我已经使用FROM B和左连接A而不是FROM A来改变连接的顺序。左连接B

SELECT  A.*, B.*, C.*, D.*  
FROM B  
LEFT  JOIN A ON B.name = A.name 
INNER JOIN C ON A.id = C.id  
INNER JOIN D ON C.id = D.id  
WHERE A.deleted=0 AND ((B.due_date < "2016-07-20" AND B.status = "Unpaid") OR (A.due_date < "2016-07-20" AND A.status = "Unpaid")) 
GROUP BY D.id    

答案 1 :(得分:1)

请使用以下查询

SELECT  A.*, B.*, C.*, D.*  
FROM A  
LEFT JOIN A_cstm ON A.id = A_cstm.id_c  
LEFT JOIN B ON B.number = A.name 
INNER JOIN C ON A_cstm.id_c = C.id
INNER JOIN D ON C.table_d_id = D.id  
WHERE A.deleted=0 AND ((B.due_date < "2016-07-20" AND B.status = "Unpaid") OR (A.due_date < "2016-07-20" AND A.status = "Unpaid")) 
GROUP BY D.id

答案 2 :(得分:0)

试试这个:

SELECT  A.*, B.*, C.*, D.*  
FROM B  
LEFT OUTER JOIN A ON A.name= B.name 
LEFT OUTER JOIN C ON C.id = B.id  
LEFT OUTER JOIN D ON D.id = B.id  
WHERE A.deleted=0 AND ((B.due_date < "2016-07-20" AND B.status = "Unpaid") OR (A.due_date < "2016-07-20" AND A.status = "Unpaid")) 
GROUP BY D.id