添加两个子查询以生成第三列

时间:2014-03-06 11:05:31

标签: mysql sql subquery

我需要从两个子查询中添加两个值并将其添加到第三列。 我可以写两次完整的子查询来产生总和,但是有更好的方法吗?

SELECT 
    d.id,
    CONCAT(d.disease, '( ', d.disease_nepali, ' ) ') AS DISEASE,
    IFNULL((SELECT 
                    patients.D_O_M + patients.D_O_F
                FROM
                    patients
                WHERE
                    clinic = 22
                        AND patients.disease = p.disease),
            0) AS 'district1',
    IFNULL((SELECT 
                    patients.D_O_M + patients.D_O_F
                FROM
                    patients
                WHERE
                    clinic = 21 AND disease = p.disease),
            0) AS 'district2'
FROM
    diseases d
        LEFT JOIN
    patients p ON (d.id = p.disease AND p.district = 9
        AND p.status = 1
        AND p.report_date LIKE '2014-03%')
GROUP BY disease

1 个答案:

答案 0 :(得分:2)

您可以使用子选择

SELECT t.*,t.district1 + t.district2  `new_col`
FROM (
SELECT d.id, CONCAT(d.disease, '( ' ,d.disease_nepali, ' ) ') AS DISEASE, 
IFNULL((SELECT patients.D_O_M+patients.D_O_F FROM patients WHERE clinic = 22 AND     patients.disease = p.disease),0) AS `district1` , 
IFNULL((SELECT patients.D_O_M+patients.D_O_F FROM patients WHERE clinic = 21 AND disease = p.disease),0) AS `district2`
 FROM diseases d
LEFT JOIN patients p ON 
(d.id = p.disease AND p.district = 9 AND p.status = 1 AND p.report_date LIKE '2014-03%') 
GROUP BY disease
) t