MYSQL如果一个选择查询返回0行然后另一个选择查询?
如果 select * from table where x=1
返回 0 行,那么我需要 select * from table where 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 .....
如果第一个结果为空,则:
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.
相关文章