MYSQL如果一个select查询返回0行然后另一个select查询? [英] MYSQL if a select query returns 0 rows then another select query?

查看:892
本文介绍了MYSQL如果一个select查询返回0行然后另一个select查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 select * from table from x = 1 返回0行,那么我需要 select * from table from x = 2 [或其他查询] 。是否可以在带有条件语句的单个MySQL查询中执行此操作?

if select * from table where x=1 returns 0 rows, then I need select * from table where x=2 [or some other query]. Is it possible to do this in a single MySQL query with a conditional statement?

编辑:所有答案 UNION 工作,但前提是两个查询都选择同一个表(或具有相同列数的表)。如果第二个查询应用于具有连接的其他表,该怎么办?

All answers with UNION work, but only if both queries select from the same table (or tables with the same number of columns). What if the second query is applied on a different table with joins?

让我写下我的查询以使问题更清晰:

Let me write down the my queries to make the question more clear:

SELECT  table1.a, table2.b  from table1 LEFT JOIN table2 ON table2.x= table1.x
WHERE ..... 

如果第1个结果一个为null然后:

if the result from the 1st one is null then:

SELECT table1.a FROM table1 
WHERE ....

我将使用第一个查询中的行如果它返回任何,否则将使用第二个。

I will be using the rows from the 1st query if it returns any, otherwise the 2nd one will be used.

推荐答案

这似乎是我刚刚做的快速测试避免需要检查两次 x = 1 的存在。

This appears to work from a quick test I just did and avoids the need to check for the existence of x=1 twice.

SELECT SQL_CALC_FOUND_ROWS *
FROM mytable
WHERE x = 1

UNION ALL

SELECT *
FROM mytable
WHERE 
FOUND_ROWS() = 0 AND x = 2;

编辑:在您澄清问题之后,显然2个查询需要与上述UNION兼容工作。

Following your clarification to the question obviously the 2 queries will need to be UNION compatible for the above to work.

您更新的问题的答案是否定的。这在单个查询中是不可能的。您需要使用一些条件程序逻辑来执行所需的查询。

The answer to your updated question is No. This is not possible in a single query. You would need to use some conditional procedural logic to execute the desired query.

这篇关于MYSQL如果一个select查询返回0行然后另一个select查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆