UNION mysql给出了奇怪的编号结果

时间:2014-08-01 22:10:17

标签: php mysql mysqli

我正在组合表格来获取他们最新的条目。下面的第一个查询工作正常。当我向其添加第三个表时,结果变得奇怪。

这个有效:

(SELECT AL.alID, AL.al_date AS ts FROM AL)
UNION
(SELECT MRA.mraNR, MRA.mra_date FROM MRA)
ORDER BY ts DESC LIMIT 20

并给出结果:

AL.alID | ts
14864 | 2014-08-01 23:43:08 
14865 | 2014-08-01 23:36:46 
2401  | 2014-08-01 18:07:06 
2401  | 2014-08-01 18:06:00 

虽然,这个查询:

(SELECT AL.alID, AL.al_date AS ts FROM AL)
UNION
(SELECT MRA.mraNR, MRA.add_date FROM MRA)
UNION
(SELECT AMG.mraNR, AMG.lastupd FROM AMG GROUP BY AMG.mraNR)
ORDER BY ts DESC LIMIT 20

...给出了这个结果,第一个nr根本没有意义:

3134383634 | 2014-08-01 23:46:20 
3134383634 | 2014-08-01 23:43:08 
3134383635 | 2014-08-01 23:38:56 
3134383635 | 2014-08-01 23:36:46 
32343031   | 2014-08-01 18:07:06 

我的问题:

  1. 如何在查询中解决此问题?
  2. 如何对结果进行分组,使其不会显示双打(AL.al​​ID)

1 个答案:

答案 0 :(得分:2)

也许这会做你想要的:

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;

它将返回20个不同的ID,其中包含三个表中任何一个的最新值。