mysql连表查询并排序问题

有两个表(还有其他字段):
第一个t1中有字段
t1_name(varchar) t1_sex(varchar) t1_birth(TimeStamp)
第二个t2中有字段
t2_name(varchar) t2_sex(varchar) t2_birth(TimeStamp)
希望查到的结果是两个表中含有三个字段 name sex birth并且按照birth排序?

select a.t1_name name,a.t1_sex sex,a.t1_birth birth from t1 a order by a.birth
UNION
select b.t2_name name,b.t2_sex sex,b.t2_birth birth from t2 b order by b.birth

select t1_name name,t1_sex sex,t1_birth birth from t1 order by birth
UNION
select t2_name name,t2_sex sex,t2_birth birth from t2 order by birth

[code="sql"]select a.t1_name name,a.t1_sex sex,a.t1_birth birth from t1 a order by a.birth
UNION ALL
select b.t2_name name,b.t2_sex sex,b.t2_birth birth from t2 b order by b.birth [/code]

性能会稍微好点 :wink:

pJun UNION ALL 为什么会好一些了

在数据库中,UNION和UNION ALL关键字都是将两个结果集合并为一个,但这两者从使用和效率上来说都有所不同。
UNION在进行表链接后会筛选掉重复的记录,所以在表链接后会对所产生的结果集进行排序运算,删除重复的记录再返回结果。
实际大部分应用中是不会产生重复的记录,最常见的是过程表与历史表UNION。如:

select * from gc_dfys

union

select * from ls_jg_dfys

这个SQL在运行时先取出两个表的结果,再用排序空间进行排序删除重复的记录,最后返回结果集,如果表数据量大的话可能会导致用磁盘进行排序。

而UNION ALL只是简单的将两个结果合并后就返回。这样,如果返回的两个结果集中有重复的数据,那么返回的结果集就会包含重复的数据了。

从效率上说,UNION ALL 要比UNION快很多,所以,如果可以确认合并的两个结果集中不包含重复的数据的话,那么就使用UNION ALL,如下:

select * from gc_dfys

union all

select * from ls_jg_dfys

[color=red]看LZ选择哪种咯[/color]