mysql (select i =0),MYSQL如果一个select查询返回0行然后另一个select查询?

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?

Edit: 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:

1st:

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

WHERE .....

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

2nd:

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.

解决方案

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;

Edit: 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值