UNION ALL - 返回结果表

时间:2015-11-30 21:30:00

标签: php mysql

我正在运行此代码(感谢@Gordon Linoff)。

SELECT alid, max(ts) as ts
FROM ((SELECT AL.alID, AL.al_date AS ts FROM AL)
      UNION ALL
      (SELECT MRA.mraNR, MRA.add_date FROM MRA)
      UNION ALL
      (SELECT AMG.mraNR, AMG.lastupd FROM AMG)
     ) t
GROUP BY alID
ORDER BY ts DESC
LIMIT 20;

现在我们需要有第三个值,知道结果来自哪个表(AL,MRA或AMG)。 已经尝试过这样的选项,但似乎没什么用。

SELECT alid, TABLEVALUEWENEED as RES, max(ts) as ts
FROM ((SELECT AL.alID, TABLEVALUEWENEED AS RES1, AL.al_date AS ts FROM AL)
      UNION ALL
      (SELECT MRA.mraNR, TABLEVALUEWENEED AS RES2, MRA.add_date FROM MRA)
      UNION ALL
      (SELECT AMG.mraNR, TABLEVALUEWENEED AS RES3, AMG.lastupd FROM AMG)
     ) t
GROUP BY alID
ORDER BY ts DESC
LIMIT 20;

并且,将这些表值作为php输出,如:

$RES1=$rows["RES1"];

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

只需将带有表名的字符串替换为TABLEVALUEWENEED

SELECT alid, RES1, max(ts) as ts
FROM ((SELECT AL.alID, 'AL' AS RES1, AL.al_date AS ts FROM AL)
      UNION ALL
      (SELECT MRA.mraNR, 'MRA' AS RES1, MRA.add_date FROM MRA)
      UNION ALL
      (SELECT AMG.mraNR, 'AMG' AS RES1, AMG.lastupd FROM AMG)
     ) t
GROUP BY alID
ORDER BY ts DESC
LIMIT 20;

我还假设您希望别名始终为'RES1'而不是'RES1','RES2','RES3',因为列的名称将是来自SELECT的第一个UNION的别名{1}}无论如何。