首页 > 解决方案 > 比较 2 个表并返回 MySQL 中的变化

问题描述

大家早上好,我希望有人可以帮助我解决以下问题。

在MySQL中,我需要比较不同员工填写的2个相同的表,并在记录有变化时返回,如果有变化,则必须返回“零件号”、“数量”并知道它属于表1还是表2. 所以我创建了一个名为“TypeTable”的不存在的列,但它返回给我 NULL。

这是查询:

SELECT numParte
    ,Cantidad
    ,NULL AS "TypeTable"
FROM (
    SELECT numParte
        ,SUM(Cantidad) AS Cantidad
        ,"TypeTable" AS "Table1"
    FROM eboard.pye_hojadecarga
    WHERE id_chklistemb = 'IDHDC-1-HY'
    GROUP BY numParte

    UNION ALL

    SELECT numParte
        ,SUM(Cantidad) AS Cantidad
        ,"Table2"
    FROM eboard.pye_hojaconfirmacion
    WHERE id_hojadecarga = 'IDHDC-1-HY'
    GROUP BY numParte
    ) tbl
GROUP BY numParte
    ,Cantidad
HAVING count(*) = 1
ORDER BY numParte;

在此处输入图像描述

标签: mysqlsqldatabaseselectunion-all

解决方案


您的外部查询不正确,它指定 NULL 作为要显示的值。而是简单地显示第三列:

SELECT numParte
     , Cantidad
     , TypeTable
FROM (
    SELECT numParte
         , SUM(Cantidad) AS Cantidad
         , 'Table1'      AS TypeTable
    FROM eboard.pye_hojadecarga
    WHERE id_chklistemb = 'IDHDC-1-HY'
    GROUP BY numParte

    UNION ALL

    SELECT numParte
         , SUM(Cantidad) AS Cantidad
         ,'Table2'       AS TypeTable
    FROM eboard.pye_hojaconfirmacion
    WHERE id_hojadecarga = 'IDHDC-1-HY'
    GROUP BY numParte
    ) tbl
GROUP BY numParte
       , Cantidad
HAVING count(*) = 1
ORDER BY numParte;

推荐阅读