当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL中使用自定义变量 编写偷懒的UNION示例

MySQL中使用自定义变量 编写偷懒的UNION示例

2017年12月12日  | 移动技术网IT编程  | 我要评论

(参考自<<高性能mysql>>)
假设有这样的需求:写一个union查询,其第一个子查询作为分支先执行,如果找到了匹配的行,则不再执行第二个分支的查询。

一般来说,我们可以写出这样的union查询:

复制代码 代码如下:

select id from users where id=123456
union all
select id from users_archived where id = 123456;

此查询可以正常运行,但是无论在users表中是否找到记录,都会到users_archived表中扫描一次;因此可能也会返回重复的记录。为了减少这种情况下不必要的开销,sql语句可以写成这样:
复制代码 代码如下:

select greatest(@found := -1, id) as id, 'users' as which_tbl
from users where id  = 1
union all
    select id, 'users_archived'
    from users_archived where id = 1 and @found is null
union all
    select 1, 'reset' from dual where (@found := null) is not nll;

上面的查询用到了自定义变量@found,通过在结果列中做一次赋值并且放在greatest函数中,以避免返回额外的数据。如果第一个分支查询结果集为null,那@found自然也还是null,因此会执行第二个分支查询。另外,为了不影响后面的遍历结果,在查询的末尾将@found重置为null。

另外, 返回的第二列数据是为了说明这条记录是在users表还是在users_archived表中查询得到的。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网