在SQL语句中使用WHERE 1 = 1的目的是什么? [英] What is the purpose of using WHERE 1=1 in SQL statements?
问题描述
可能的重复项:
为什么sql查询会有哪里1 = 1
为什么有人会使用WHERE 1 = 1 AND< conditions"在SQL子句中?
我在不同的查询示例中看到了很多,而且可能涉及所有SQL
I've seen that a lot in different query examples and it goes to probably all SQL engines.
如果存在没有条件定义的查询,人员(尤其是ORM框架)通常会添加始终为真的条件 WHERE 1 = 1 或类似的东西。
If there is a query that has no conditions defined people (and specially ORM frameworks) often add always-true condition WHERE 1 = 1
or something like that.
因此,而不是
SELECT id, name FROM users;
使用
SELECT id, name FROM users WHERE 1 = 1;
我想到的唯一可能的理由是,如果您动态添加条件,则不必担心关于剥离初始 AND
的操作,但如果在实际操作中存在实际条件,则通常会剥离此 1 = 1
条件查询。
The only possible reason I could think of if you are adding conditions dynamically you don't have to worry about stripping the initial AND
but still quite often this 1 = 1
condition is stripped if there is an actual condition in the query.
来自CakePHP的实际示例(由框架生成):
Actual example from CakePHP (generated by framework):
(无条件)
SELECT `User`.`id`, `User`.`login`
FROM `users` AS `User` WHERE 1 = 1
ORDER BY `User`.`id` ASC;
(有条件)
SELECT `User`.`id`, `User`.`login`
FROM `users` AS `User`
WHERE `User`.`login` = 'me@example.com'
LIMIT 1;
是否有任何理由要添加该额外条件?
Is there any reason for adding that extra condition?
推荐答案
是的,通常是因为它以'where 1 = 0'开始,迫使语句失败。
Yeah, it's typically because it starts out as 'where 1 = 0', to force the statement to fail.
这是一种比较幼稚的方法,可以将其包装在事务中而不在最后提交它,以测试您的查询。 (这是首选方法)。
It's a more naive way of wrapping it up in a transaction and not committing it at the end, to test your query. (This is the preferred method).
这篇关于在SQL语句中使用WHERE 1 = 1的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!