Second SELECT query if first SELECT returns 0 rows(如果第一个 SELECT 返回 0 行,则第二个 SELECT 查询)
问题描述
我正在尝试加快 PHP 脚本的运行速度,目前我正在该事物的 Mysql 域中推送一些 PHP 逻辑.如果第一个 Select 不返回行或计数为零,是否有办法进行不同的选择查询?
I am trying to speed up a PHP script and I am currently pushing some PHP logic in the Mysql domain of the thing. Is there a way to make a different select query if the first Select returns no rows, or a count of zero ?
请记住,第一个查询需要先运行,第二个查询应该仅在第一个查询返回空集时激活.
Keeping in mind that the first query needs to run first, and the second should only be activated if the first one returns an empty set.
SELECT * FROM proxies WHERE (A='B') || SELECT * FROM proxies WHERE (A='C')
对于上面的 2 个查询,我有这个代码,但它似乎每个查询运行两次(一次计数,一次返回).有没有更好的方法来做到这一点?
For the above 2 queries I have this code, but it seems to run each query twice (once to count, and once to return). Is there a better way to do this?
IF (SELECT count(*) FROM proxies WHERE A='B')>0
THEN SELECT * FROM proxies WHERE A='B'
ELSEIF (SELECT count(*) FROM proxies WHERE A='C')>0
THEN SELECT * FROM proxies WHERE A='C'
END IF
推荐答案
一种选择是将 UNION ALL 与 EXISTS 一起使用:
One option would be to use UNION ALL with EXISTS:
SELECT *
FROM proxies
WHERE A='B'
UNION ALL
SELECT *
FROM proxies
WHERE A='C' AND NOT EXISTS (
SELECT 1
FROM proxies
WHERE A='B'
)
- SQL Fiddle 演示
这将返回 proxies 表中的行,其中 A='B' 如果它们存在.但是,如果它们不存在,它将查找那些带有 A='C' 的行.
This will return rows from the proxies table where A='B' if they exist. However, if they don't exist, it will look for those rows with A='C'.
这篇关于如果第一个 SELECT 返回 0 行,则第二个 SELECT 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果第一个 SELECT 返回 0 行,则第二个 SELECT 查询
基础教程推荐
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
