在一个结果集中的不同行上多次连接表

时间:2012-06-14 03:28:10

标签: mysql group-by outer-join

所以我有2张桌子(简化如下)

members                     documents
------------                ------------------
id | name | registered      id | member_id | type | expiry
----------------------      ------------------------------
1  | AAA  | 1234567890      1  | 1         | 1    | 1234567890
2  | BBB  | 1234567890      2  | 1         | 2    | 1234567891
3  | CCC  | 1234567890      3  | 1         | 3    | 1234567892
                            4  | 2         | 1    | 1234567893
                            5  | 2         | 2    | 1234567894
                            6  | 2         | 3    | 1234567890

我需要这样显示:

member id | name | doc 1 expiry | doc 2 expiry | doc 3 expiry 
--------------------------------------------------------------
1         | AAA  | 1234567890   | 1234567891   | 1234567892
2         | BBB  | 1234567893   | 1234567894   | 1234567895

我尝试使用多个外连接和别名进行查询,但它只是重复文档到期时间戳。这就是我到目前为止所做的:

    SELECT DISTINCT `members`.`id`, `members`.`name`, `a`.`expiry` AS `expiry1`, `b`.`expiry` AS `expiry2`, `c`.`expiry` AS `expiry3` 
    FROM `members` 
    LEFT OUTER JOIN `documents` a ON `a`.`member_id` = `members`.`id` 
    LEFT OUTER JOIN `documents` b ON `b`.`member_id` = `members`.`id` 
    LEFT OUTER JOIN `documents` c ON `c`.`member_id` = `members`.`id` 
    GROUP BY `members`.`id`

人们需要能够搜索到这一点,例如列出文档类型3已过期的所有人。

1 个答案:

答案 0 :(得分:0)

尝试

SELECT 
    a.id AS 'member id',
    a.name
    SUM(a.d1exp) AS 'doc 1 expiry',
    SUM(a.d2exp) AS 'doc 2 expiry',
    SUM(a.d3exp) AS 'doc 3 expiry'
FROM
    (
        SELECT 
            aa.id,
            aa.name,
            COALESCE(d1.expiry, 0) AS d1exp,
            COALESCE(d2.expiry, 0) AS d2exp,
            COALESCE(d3.expiry, 0) AS d3exp
        FROM
            members aa
        LEFT JOIN
            documents d1 ON aa.id = d1.member_id AND d1.type = 1
        LEFT JOIN
            documents d2 ON aa.id = d2.member_id AND d2.type = 2
        LEFT JOIN
            documents d3 ON aa.id = d3.member_id AND d3.type = 3
    ) a
GROUP BY
    a.id,
    a.name

这假设'到期'字段中的值是数字。