MySQL双LEFT OUTER JOIN

时间:2012-01-18 12:24:45

标签: mysql sql join

我有两个表个人资料名称,个人资料表包含一些与用户相关的元数据。名称表包含配置文件可能具有的所有可能名称。

我正在尝试创建 MYSQL 查询,该查询将为我提供profile.age,所有配置文件的给定名称和系列名称,即使它没有给定的名称或姓氏

资料


    +-------+---------+
    | ID    | AGE     | 
    +-------+---------+
    | 0     |  10     |
    | 1     |  20     |
    | 2     |  30     |
    | 3     |  40     |
    +-------+---------+  


名称


    +------------+--------+--------+
    | PROFILE_ID |  TYPE  |  NAME  | 
    +------------+--------+--------+
    |      0     |   0    | Jo     |
    |      0     |   1    | Blog   |
    |      1     |   0    | Jim    |
    |      2     |   1    | Smith  |
    +------------+--------+--------+

    Type 0 = Given Name
    Type 1 = Family Name

Quert

这是我目前使用的查询。

SELECT given.name AS 'given_name', family.name AS 'family_name', profile.age
FROM profile
LEFT OUTER JOIN name given ON profile.id = given.profile_id
LEFT OUTER JOIN name family ON profile.id = family.profile_id
WHERE given.type = 0 
AND profile_id.type = 1 
LIMIT 0 , 30

问题

这是我想要的结果


    +------------+-------------+--------+
    | GIVEN_NAME | FAMILY_NAME | ADE    |
    +------------+-------------+--------+
    | Jo         | Blog        | 10     |
    | Jim        | NULL        | 20     |
    | NULL       | Smith       | 30     |
    | NULL       | NULL        | 40     |
    +------------+-------------+--------+

然而,这是我实际得到的


    +------------+-------------+--------+
    | GIVEN_NAME | FAMILY_NAME | AGE    |
    +------------+-------------+--------+
    | Jo         | Blog        | 10     |
    +------------+-------------+--------+

根据我的理解 LEFT OUTER JOIN 应该返回NULL值连接。我究竟做错了什么?如何更改查询以返回NULL值joun?

3 个答案:

答案 0 :(得分:5)

您将type过滤为0或1(在where子句中),这将忽略null s。

SELECT given.name AS 'given_name', family.name AS 'family_name', profile.age
    FROM profile
    LEFT OUTER JOIN name given 
       ON profile.id = given.profile_id and given.type = 0 
    LEFT OUTER JOIN name family 
       ON profile.id = family.profile_id and profile.type = 1 
    LIMIT 0 , 30

答案 1 :(得分:4)

只要在WHERE上的表上有LEFT JOIN子句,您就会立即消除NULL行(即没有匹配的行)。因此对于初学者,您应该将given.type = 0的条件移到ON子句而不是WHERE子句中。而且我将假设WHERE条款中的其他条件存在问题。

SELECT given.name AS 'given_name', family.name AS 'family_name', profile.age
FROM profile
LEFT OUTER JOIN name given ON profile.id = given.profile_id AND given.type = 0 
LEFT OUTER JOIN name family ON profile.id = family.profile_id AND family.type = 1
LIMIT 0 , 30

答案 2 :(得分:-2)

SELECT N1.id, N1.name,N2.name, A3.age 
FROM name N1, name N2, age A3 
WHERE N1.id=N2.id AND N1.id=A3.id 
  AND N1.type=0   AND N2.type=1

name指的是名称表 age指的是个人资料表