结合两个sql查询

时间:2013-11-10 17:17:44

标签: mysql sql

有人可以帮我把这两个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

1 个答案:

答案 0 :(得分:1)

将您的第一个查询换入子查询并使用LEFT JOIN加入,以便所有不匹配的记录仍会显示,但0中的值为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