MySQL 如何选择一个空的结果集?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1456106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select an empty result set?
提问by Petruza
I'm using a stored procedure in MySQL, with a CASE statement.
我在 MySQL 中使用存储过程,并带有 CASE 语句。
In the ELSE clause of the CASE ( equivalent to default: ) I want to select and return an empty result set, thus avoiding to throw an SQL error by not handling the ELSE case, and instead return an empty result set as if a regular query would have returned no rows.
在 CASE 的 ELSE 子句中(相当于 default: )我想选择并返回一个空的结果集,从而避免通过不处理 ELSE 案例来抛出 SQL 错误,而是像常规查询一样返回一个空的结果集不会返回任何行。
So far I've managed to do so using something like:Select NULL From users Where False
到目前为止,我已经设法使用以下方法做到了:Select NULL From users Where False
But I have to name an existing table, like 'users' in this example. It works, but I would prefer a more elegant way that doesn't break if eventually the table name used is renamed or dropped.
但我必须命名一个现有的表,如本例中的“用户”。它有效,但我更喜欢一种更优雅的方式,如果最终使用的表名被重命名或删除,则不会中断。
I've tried Select NULL Where False
but it doesn't work.
我试过了,Select NULL Where False
但它不起作用。
Using Select NULL
does not return an empty set, but one row with a column named NULL and with a NULL value.
UsingSelect NULL
不会返回一个空集,而是返回一个包含名为 NULL 的列和一个 NULL 值的行。
采纳答案by Bj?rn
There's a dummy-table in MySQL called 'dual', which you should be able to use.
MySQL 中有一个名为“dual”的虚拟表,您应该可以使用它。
select
1
from
dual
where
false
This will always give you an empty result.
这总是会给你一个空的结果。
回答by Aleh
This should work on most DBs, tested on Postgres and Netezza:
这应该适用于大多数数据库,在 Postgres 和 Netezza 上测试过:
SELECT NULL LIMIT 0;
回答by irrelevantthesis
T-SQL (MSSQL):
T-SQL (MSSQL):
SELECT Top 0 1;
回答by Maksee
How about
怎么样
SELECT * FROM (SELECT 1) AS TBL WHERE 2=3
Checked in myphp, and it also works in sqlite and probably in any other db engine.
在 myphp 中检查,它也适用于 sqlite 和可能适用于任何其他数据库引擎。
回答by Tim
SELECT NULL WHERE FALSE;
it works in postgresql ,mysql, subquery in mysql.
它适用于 postgresql ,mysql,mysql 中的子查询。
回答by dhruvbird
This will probably work across all databases.
这可能适用于所有数据库。
SELECT * FROM (SELECT NULL AS col0) AS inner0 WHERE col0 IS NOT NULL;
回答by Nilesh
SELECT TOP 0 * FROM [dbo].[TableName]
This is a reasonable approach to constant scan operator.
这是恒定扫描算子的合理方法。
回答by Raj More
How about this?
这个怎么样?
SELECT 'MyName' AS EmptyColumn
FROM dual
WHERE 'Me' = 'Funny'
回答by aasfalcon
SELECT * FROM (SELECT NULL) WHERE 0
回答by luckydonald
In PostgreSQL a simple
在 PostgreSQL 中一个简单的
SELECT;
works. You won't even get any columns labeled 'unknown'.
Note however, it still says 1 row retrieved.
作品。您甚至不会得到任何标记为“未知”的列。
但是请注意,它仍然说检索到 1 行。