0

有人可以帮我将这两个sql查询组合起来,将第一个查询的结果放入第二个查询的列中,谢谢

SELECT
    `c`.`backoffice_users_id`,
    sum(c.nbr_sous_risques) AS `nbr_sous_risques`
FROM `conseillers_sous_risques` AS `c`
WHERE
    (c.date_du_jour='2013-11-10')
    AND (c.idsous_risques BETWEEN 1 AND 12)
GROUP BY `c`.`backoffice_users_id`


SELECT
    `c`.`backoffice_users_id`,
    `c`.`idsous_risques`,
    `c`.`nbr_sous_risques`,
    `backoffice_users`.`lastname`
FROM `conseillers_sous_risques` AS `c`
INNER JOIN `backoffice_users` ON c.backoffice_users_id=backoffice_users.id
WHERE (c.date_du_jour='2013-11-10')
ORDER BY
    `c`.`backoffice_users_id` ASC,
    `c`.`idsous_risques` ASC
4

1 回答 1

1

将您的第一个查询包装在子查询中并使用它连接它,LEFT JOIN这样任何不匹配的记录仍将显示,但值为0in nbr_sous_risques

SELECT  c.backoffice_users_id, 
        c.idsous_risques, 
        c.nbr_sous_risques, 
        backoffice_users.lastname,
        COALESCE(d.nbr_sous_risques, 0) nbr_sous_risques
FROM    conseillers_sous_risques AS c
        INNER JOIN backoffice_users 
            ON c.backoffice_users_id = backoffice_users.id 
        LEFT JOIN
        (
            SELECT  c.backoffice_users_id, 
                    SUM(c.nbr_sous_risques) AS nbr_sous_risques 
            FROM    conseillers_sous_risques AS c 
            WHERE   c.date_du_jour='2013-11-10' AND 
                    c.idsous_risques BETWEEN 1 AND 12
            GROUP   BY c.backoffice_users_id
        ) d ON  c.backoffice_users_id = d.backoffice_users_id
WHERE   c.date_du_jour='2013-11-10'
ORDER   BY c.backoffice_users_id ASC, c.idsous_risques ASC
于 2013-11-10T17:26:50.737 回答