SQL 中的“WHERE 1”是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3720735/
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
What does "WHERE 1" mean in SQL?
提问by Emanuil Rusev
Sometimes phpMyAdmin generates queries like:
有时 phpMyAdmin 会生成如下查询:
SELECT *
FROM `items`
WHERE 1
LIMIT 0 , 30
I wonder if WHERE 1
has any meaning in a query like that.
我想知道这样WHERE 1
的查询是否有任何意义。
回答by Pablo Santa Cruz
It doesn't. It means ALWAYS TRUE
so it won't have any filtering impact on your query. Query planner will probably ignore that clause.
它没有。这意味着ALWAYS TRUE
它不会对您的查询产生任何过滤影响。查询规划器可能会忽略该子句。
It's usually used when you build a client side query by concatenating filtering conditions.
当您通过连接过滤条件构建客户端查询时,通常会使用它。
So, if your base query is stored in a string like this (example is in PHP, but it certainly applies to many other languages):
因此,如果您的基本查询存储在这样的字符串中(示例是在 PHP 中,但它当然适用于许多其他语言):
$sql = "select * from foo where 1 ";
Then you can just concatenate a lot of filtering conditions with an AND
clause regardless of it being the first condition you are using or not:
然后,您可以将许多过滤条件与AND
子句连接起来,而不管它是否是您使用的第一个条件:
// pseudo php follows...
if ($filter_by_name) {
$sql = $sql . " and name = ? ";
}
if ($filter_by_number) {
$sql = $sql . " and number = ? ";
}
// so on, and so forth.
回答by Paul Schreiber
WHERE 1
is a synonym for "true" or "everything."
WHERE 1
是“真实”或“一切”的同义词。
It's a shortcut so they don't have to remove the where clause from the generated SQL.
这是一个快捷方式,因此他们不必从生成的 SQL 中删除 where 子句。
Otherwise, you would write something like this:
否则,你会写这样的东西:
$sql = "SELECT * FROM `errors`";
if ($hasWhereClause == true) {
$sql .= " WHERE $whereClause";
}
$sql .= "LIMIT 0 , 30";
回答by flq
I'd guess it's a string-concatenation artefact: if no where conditions are specified, a "1" is output. That way it does not have to be decided whether the WHERE keyword should be output or not.
我猜这是一个字符串连接人工制品:如果没有指定 where 条件,则输出“1”。这样就不必决定是否应该输出 WHERE 关键字。
Also you can always output it and simply concatenate conditions with "AND" and "OR". You don't have to decide that the first condition should not start with AND, OR keyword.
您也可以随时输出它并简单地将条件与“AND”和“OR”连接起来。您不必决定第一个条件不应以 AND、OR 关键字开头。