怎样实现如果一条查询语句结果集为空则执行另一条查询语句

yk2045 2017-11-24 07:14:31
我想用一条语句实现如果第一条语句查询为空则执行第二条查询语句。

第一条
select name from tiaoche where id>(select id from tiaoche where name=(select tiaochegong from paichebiao order by time desc limit 1)) order by id asc limit 2

第二条
select name from tiaoche where id=(select min(id)from tiaoche)

需求是,拿到比上一条数据中更大的数,如果已经是最大,则取最小的数。
...全文
1850 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_41671114 2019-03-08
  • 打赏
  • 举报
回复
黄金客户空间和客户
[align=center]
[/align]
zjcxc 2017-11-27
  • 打赏
  • 举报
回复
上面的查询可以达到要求,但第1个查询执行了两次,如果你想查询效率好些,那程序上得花点功夫 比如下面这样,程序只发出一次查询(2条 sql, 需要支持批查询, 但这个查询始终是两个结果集,程序上需要判断第一个结果集不为空是取第2个 )
select name from tiaoche where id>(select id from tiaoche where name=(select tiaochegong from paichebiao order by time desc limit 1)) order by id asc limit 2 ;
select name from tiaoche where id=(select min(id)from tiaoche) and found_rows() = 0;
zjcxc 2017-11-27
  • 打赏
  • 举报
回复
select name from tiaoche where id>(select id from tiaoche where name=(select tiaochegong from paichebiao order by time desc limit 1)) order by id asc limit 2  
union all
select name from tiaoche where id=(select min(id)from tiaoche)
where not exists(
select name from tiaoche where id>(select id from tiaoche where name=(select tiaochegong from paichebiao order by time desc limit 1)) order by id asc limit 2  
)
yk2045 2017-11-26
  • 打赏
  • 举报
回复
用代码去实现当然可以了,可是最少需要发送两条语句,如果用一句SQL语句就能查到不是更好吗?
jc小成 2017-11-26
  • 打赏
  • 举报
回复
是代码去实现 不可以吗

56,937

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧