如何在MySQL中将两个不同的表组合在一起并对其进行排序 [英] how to combine and sort two different tables together in Mysql

查看:921
本文介绍了如何在MySQL中将两个不同的表组合在一起并对其进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有表A:

id username firstname event_date
1   Ben      lori     2014-01-27
2   Ben      lori     2014-01-04
3   Mary     john     2014-01-28

我有表B:

   id username event_date
   1   Ben     2014-01-23
   2   Nicole  2014-01-26

我希望结果是这样的:是否有任何解决方案可以让我像一张桌子一样根据event_date对其进行组合和排序,如下所示:

I want the result to be like this: Is there any solution that allow me to combine and sort it according to event_date like one table,like this:

  2   Ben      lori     2014-01-04     
            1   Ben     2014-01-23
            2   Nicole  2014-01-26
  1   Ben      lori     2014-01-27
  3   Mary     john     2014-01-28

以便我可以使用诸如while循环或mysql_fetch_assoc之类的内容来显示内容

so that I can use something like while loop or mysql_fetch_assoc to display the content

推荐答案

基本上,您需要union all:

select id, username, firstname, event_date
from ((select id, username, firstname, event_date
       from tablea
      ) union all
      (select id, username, NULL as firstname, event_date
       from tablea
      )
     ) t
order by event_date;

这篇关于如何在MySQL中将两个不同的表组合在一起并对其进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆