在 SQL 语句中使用 WHERE 1=1 的目的是什么? [英] What is the purpose of using WHERE 1=1 in SQL statements?

查看:24
本文介绍了在 SQL 语句中使用 WHERE 1=1 的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
为什么一个sql查询会有“where 1 = 1”
为什么有人会使用 WHERE 1=1AND <条件>在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆