UNION mysql gives weird numbered results

穿精又带淫゛_ 提交于 2019-12-25 18:46:29

问题


I am combining tables to get all their latest entries. The first query below works fine. When I add a third table to it the results get weird.

This one works:

(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

And gives result:

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 

While, this query:

(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

...gives this result, where the first nr doesn't make sense at all:

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 

My questions:

  1. how can I solve this in the query?
  2. how can I group the results so it won't show the doubles (AL.alID)

回答1:


Perhaps this will do what you want:

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;

It will return 20 distinct ids with the latest values in any of the three tables.



来源:https://stackoverflow.com/questions/25089417/union-mysql-gives-weird-numbered-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!