What is wrong with the following SQL left join?

时间:2016-05-11 11:31:27

标签: sql join

I have 5 tables: A, B, C, D, E

A: {ID, Value, GroupID, FilterID, In_Date}

B: {ID, Description, Out_Date, From_Date }

C: {ID, Category}

D: {GroupID, GroupName}

E: {FilterID, FilterName}

There could be missing IDs in B and C as a result, I'm trying to do a LEFT JOIN to get the required info. In my dataset, I've explicitly added a row in A with ID that's not in B or C. I expect it to be picked up in the following query, but it doesn't happen. I believe I'm going wrong in the WHERE clause due to null values in B and C.

SELECT A.Value, A.Group, B.Description, C.Category, D.GroupName, E.FilterName 
FROM A LEFT JOIN B ON A.ID = B.ID     
       LEFT JOIN C ON A.ID = C.ID,
     D,E
WHERE
B.Out_Date>A.In_Date,
A.GroupID=D.GroupID,
A.FilterID=E.FilterID

How can I fix this to retrieve the fields I want with null values when the ID is not in B or C , but in A?

4 个答案:

答案 0 :(得分:1)

1) Don't mix old comma separated join syntax with modern explicit join syntax!

2) When left join, put the right side table's conditions in the ON clause to get true left join behavior. (When in WHERE you get inner join result.)

SELECT A.Value, A.Group, B.Description, C.Category, D.GroupName, E.FilterName 
FROM A LEFT JOIN B ON A.ID = B.ID AND B.Out_Date > A.In_Date
       LEFT JOIN C ON A.ID = C.ID
       JOIN D ON A.GroupID = D.GroupID
       JOIN E ON A.FilterID = E.FilterID

Value and Group are reserved words in ANSI SQL, so you may need to delimit them, as "Value" and "Group".

答案 1 :(得分:1)

First point: You shouldn't mix join syntaxes, just use explicit syntax.

Because of your where clause, you effectively turn your left joins in inner joins. You are probably looking for:

SELECT     A.Value, A.Group, B.Description, C.Category, D.GroupName, E.FilterName 
FROM       A 
LEFT JOIN  B 
       ON  A.ID = B.ID 
       AND B.Out_Date > A.In_Date
LEFT JOIN  C 
        ON A.ID = C.ID
INNER JOIN D
        ON A.GroupID = D.GroupID
INNER JOIN E
        ON A.FilterID = E.FilterID

答案 2 :(得分:1)

您可以将此查询用于您的问题。

SELECT     A.Value, A.Group, B.Description, C.Category, D.GroupName, E.FilterName 
FROM       A 
LEFT JOIN  B 
   ON  A.ID = B.ID 
   AND B.Out_Date > A.In_Date
LEFT JOIN  C 
    ON A.ID = C.ID
LEFT JOIN D
    ON A.GroupID = D.GroupID
LEFT JOIN E
    ON A.FilterID = E.FilterID

答案 3 :(得分:1)

这是您的表格详情

A:{ID,Value,GroupID,FilterID,In_Date}

B:{ID,Description,Out_Date,From_Date}

C:{ID,Category}

D:{GroupID,GroupName}

E:{FilterID,FilterName}

现在您尝试使用左连接检索数据 所以你试试流动的剧本

      SELECT A.Value, A.Group, B.Description, C.Category, D.GroupName,E.FilterName from A left join B on A.ID=B.ID
left Join C on A.ID=C.ID
Left Join D on A.GroupID=D.GroupID
Left Join E on A.FilterID=E.FilterID
where B.Out_Date>A.In_Date

我希望这对你有帮助。

相关问题