Home > Database > Mysql Tutorial > body text

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

WBOY
Release: 2016-06-01 13:25:21
Original
975 people have browsed it

bitsCN.com

(参考自>)
假设有这样的需求:写一个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表中查询得到的。

bitsCN.com
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template