MySQL从两个表中选择数据并统一排序


问题是这样的,我打算在一个表里获得与某一行记录相邻的两行,并且想通过union一起取出来,所以这么写:

select id,title from subjects where id>#some_id# order by id limit 1

union

select id,title from subjects where id<#some_id# order by id limit 1

但出现了错误提示“Incorrect usage of UNION and ORDER BY”。看来不能这么用union和order by,但这里确实是需要order by的。很快,我想到了一个变通的写法:

select * from (

select id,title from subjects where id>#some_id# order by id limit 1

) union

select id,title from subjects where id<#some_id# order by id limit 1

从经验上说,第二个子句该不会被union影响,可以用order by。于是把第一个子句包在一个括号里,这下应该就可以了。可是还是有错误,提示“ Every derived table must have its own alias”。这里的提示是需要给我们括号里面生成的临时表取一个别名,这个好办多了。于是改为:

select * from (

select id,title from subjects where id>#some_id# order by id limit 1

) as t1 union

select id,title from subjects where id<#some_id# order by id limit 1

相关内容