- content
说明
sybn sql 支持在子查询(如 @last、@table、from (select ...))的右括号后追加 where / order by / limit 子句,对子查询的结果集进行过滤、排序、分页。
这种后置子句无需把子查询包装成额外的 select,语法更简洁。
语法
-- 后置 where
... from (select ...) where 条件
-- 后置 order by
... from (select ...) order by 字段 [asc|desc]
-- 后置 limit
... from (select ...) limit N
-- 组合使用
... from (select ...) where 条件 order by 字段 [asc|desc] limit N
后置子句支持 mybatis 参数替换(
${param}/#{param})。
例子
-- 后置 where + order by + limit 组合
select * from (
select 'tab1' as t
union select 'tab2' as t
union select 'tab3' as t
) where t != 'tab1' order by t desc limit 1;
-- 结果:[{t:'tab3'}]
-- 后置 order by + limit
select * from (
select 'tab1' as t union select 'tab2' as t union select 'tab3' as t
) order by t desc limit 1;
-- 结果:[{t:'tab3'}]
-- 后置 limit
select * from (
select 'tab1' as t union select 'tab2' as t union select 'tab3' as t
) limit 1;
-- 结果:[{t:'tab1'}]
-- 支持 mybatis 变量替换
select * from (
select 'tab1' as t union select 'tab2' as t union select 'tab3' as t
) where t != ${val} order by t desc limit 1;
-- 当 val='tab1' 时,结果:[{t:'tab3'}]
注意事项
- 后置 where/order by/limit 作用于紧邻的子查询,不是整个语句。
- 三个子句可以任意组合,顺序为 where → order by → limit。
- 与标准 SQL 的子查询写法等价,只是语法更简洁——不需要再写一层
select * from (...)。 - 后置 where 支持 mybatis 变量替换,方便动态传参。