Left Self Join每个'primary'返回一行

时间:2015-07-11 18:10:48

标签: mysql mariadb

我有一张如下表:

Rel_Id  Last    First   Relation
1   Jones   John    Primary
1   Jones   Mary    Spouse
1   Jones   Carl    Dependent
2   Will    Bill    Primary
3   Fine    Howard  Primary
4   Smith   Diana   Primary
4   Smith   Axel    Spouse

我正在尝试返回所有“主要”关系,每行一个,但如果有一个,请将Spouse包含在同一行中。

我想要达到的结果如下:

1   Jones   John    Primary Jones   Mary    Spouse
2   Will    Bill    Primary null    null    null
3   Fine    Howard  Primary null    null    null
4   Smith   Diana   Primary Smith   Axel    Spouse

或者这也没关系:

1   Jones   John    Primary Jones   Mary    Spouse
2   Will    Bill    Primary Will    Bill    Primary
3   Fine    Howard  Primary Fine    Howard  Primary
4   Smith   Diana   Primary Smith   Axel    Spouse

这是我的疑问:

SELECT
P.Rel_Id,
P.Last,
P.`First`,
P.Relation,
S.Last AS sLast,
S.`First` AS sFirst,
S.Relation AS sRelation
FROM
relations AS P
LEFT JOIN relations AS S ON S.Rel_Id = P.Rel_Id
WHERE P.Relation = 'Primary' 
AND S.Relation <> 'Dependent'

以上查询结果为:

1   Jones   John    Primary Jones   John    Primary
1   Jones   John    Primary Jones   Mary    Spouse
2   Will    Bill    Primary Will    Bill    Primary
3   Fine    Howard  Primary Fine    Howard  Primary
4   Smith   Diana   Primary Smith   Diana   Primary
4   Smith   Diana   Primary Smith   Axel    Spouse

不幸的是,我的查询在正确排除'Dependent'的情况下显示了两行,其中有一个独特的'Primary'成员,其中有一个Spouse,我不想要。如果每个'Primary'关系只返回一行,只有一个Spouse如果还有一个吗?

3 个答案:

答案 0 :(得分:0)

您需要在连接条件中在查询中添加其他检查,以便不显示两个Primary,并且仅显示配偶。

因此,在查询中添加此条件:

S.Relation <> P.Relation

所以最终的查询将成为:

SELECT
P.Rel_Id,
P.Last,
P.`First`,
P.Relation,
S.Last AS sLast,
S.`First` AS sFirst,
S.Relation AS sRelation
FROM
relations AS P
LEFT JOIN relations AS S ON S.Rel_Id = P.Rel_Id AND S.Relation <> P.Relation
WHERE P.Relation = 'Primary' 
AND S.Relation <> 'Dependent'

希望这有帮助。

答案 1 :(得分:0)

SELECT  GROUP_CONCAT(CONCAT_WS(' ',
                               last, first, relation),
                     SEPARATOR ' -- '
                     ORDER BY IF(relation = 'PRIMARY', 0, rel_id)
        ) AS Family
    FROM relations
    GROUP BY last;

它没有给你&#34;列&#34;就像你要求的那样,但它可能会这样做。

这将处理任何人数的家庭。但是,它取决于last是唯一的。 (这是架构设计中存在的一个缺陷。)

last分开可能会更好:

SELECT  last,
        GROUP_CONCAT(CONCAT_WS(' ',
                               first, relation),
                     SEPARATOR ' -- '
                     ORDER BY IF(relation = 'PRIMARY', 0, rel_id)
        ) AS Family
    FROM relations
    GROUP BY last;

答案 2 :(得分:0)

现在看起来很明显 - 而且很简单! (非常感谢 - 真的)

SELECT
P.Rel_Id,
P.Last,
P.`First`,
P.Relation,
S.Rel_Id AS sRel_Id,
S.Last AS sLast,
S.`First` AS sFirst,
S.Relation AS sRelation
FROM
relations AS P
LEFT JOIN relations AS S ON S.Rel_Id = P.Rel_Id and S.Relation = 'Spouse'
WHERE P.Relation = 'Primary'