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.
相关文章