如何将其他表中的数据添加到双单表MySQL查询?

时间:2018-02-07 02:15:22

标签: mysql database join

我有这个功能性查询:

SELECT t1.material, t1.totalS, t2.totalH, (t1.totalS + t2.totalH) as producto, t1.fecha_dbfS, t2.fecha_dbfH FROM (SELECT material, STR_TO_DATE(fe_contab, '%d-%m-%Y') AS fecha_dbfS, SUM(impteml) AS TotalS FROM datos WHERE d_h ='S' GROUP BY material) as t1, (SELECT material, STR_TO_DATE(fe_contab, '%d-%m-%Y') AS fecha_dbfH, SUM(impteml) AS TotalH FROM datos WHERE d_h ='H' GROUP BY material) as t2 WHERE t1.material = t2.material and t1.fecha_dbfS >= '$fechai'and t1.fecha_dbfS <= '$fechaf' and t2.fecha_dbfH >= '$fechai' and t2.fecha_dbfH <= '$fechaf'

显示这样的数据(DTR =材料)Query Result

我有另一个名为nombre_dtr的表,它的数据排列如下:

nombre_dtr table data example

我需要将第一个表(查询结果)添加到nombre_dtr表中作为&#34; nombre&#34;存储的DTR的名称,使用该表上的DTR字段数学&#34;材料&#34; &#34;数据&#34;上的字段桌子,我尝试左和内连接,但没有运气。

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

您可以使用带有case语句的聚合函数和连接表nombre_dtr来实际简化查询,以便按nombre

获取列material
SELECT  d.material,
        n.nombre,
        SUM(CASE WHEN d.d_h = 'S' THEN d.impteml ELSE 0 END) AS TotalS,
        SUM(CASE WHEN d.d_h = 'H' THEN d.impteml ELSE 0 END) AS TotalH,
        SUM(d.impteml) AS producto,
        MAX(CASE WHEN d.d_h = 'S' THEN STR_TO_DATE(d.fe_contab, '%d-%m-%Y') END) fecha_dbfS,
        MAX(CASE WHEN d.d_h = 'H' THEN STR_TO_DATE(d.fe_contab, '%d-%m-%Y') END) fecha_dbfH
FROM    datos d
        INNER JOIN nombre_dtr n
            ON d.material = n.dtr
WHERE   STR_TO_DATE(d.fe_contab, '%d-%m-%Y') >= '$fechai'
        AND STR_TO_DATE(d.fe_contab, '%d-%m-%Y') <= '$fechaf' 
GROUP   BY d.material, n.nombre

这是关于SQL Join的指南。