0

所以我有 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 已过期的每个人。

4

1 回答 1

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

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

于 2012-06-14T03:40:49.090 回答