Maison > base de données > tutoriel mysql > le corps du texte

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

WBOY
Libérer: 2016-06-01 13:25:21
original
939 Les gens l'ont consulté

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
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!