请教:两张表的组合查询问题
数据库中有两张表,结构如下:
table1
id title content flag stime
1 aa1 a1xxxxx 1 2007-02-12
2 aa2 a2xxxxx 1 2007-02-12
3 aa3 a3xxxxx 1 2007-02-12
........
table2
id title content btime
1 aa1 b1xxxxx 2007-02-14
2 aa2 b2xxxxx 2007-02-14
3 aa2 b2ggggg 2007-02-15
4 aa1 b1ggggg 2007-02-13
5 aa3 b3xxxxx 2007-02-14
........
table1,table2 记录没有规律,也没有关联,字段只有几个是相同的。我想查询处如下结果:
resultTable:
title content stime btime
aa1 a1xxxxxx 2007-02-12
aa1 b1xxxxxx 2007-02-14
aa2 a2xxxxxx 2007-02-12
aa2 b2xxxxxx 2007-02-14
aa2 b2gggggg 2007-02-14
------解决方案--------------------select * from
(select title,content,stime,btime=null from table1
union all
select title,content,stime=null,btime from table2) a
order by title
------解决方案----------------------先按title排序,再按时间先后排序
select *
from
(
select title,content,stime,null as btime from table1
union all
select title,content,null stime,btime from table2
) a
order by title,case when stime is not null then 0 else 1 end, btime