mysql—非典型mysql查询的执行顺序

cidc1ykv  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(225)

假设我们有一个具有以下模式的表:

create table Test(id integer, title varchar(100));
insert into Test(id, title) values(1, "Hello");
insert into Test(id, title) values(20, "Hi");

在这种情况下,不典型的查询是:

select * from Test where id= 20 < 2 AND SLEEP(1000000000) ;
-- sleep is being executed
select * from Test where id= 20 > 2 AND SLEEP(1000000000) ;
-- sleep is not being executed and nothing is going to be display
select * from Test where id = 20  > 0;
-- shows only one record , where id=20 /// "Hi"
select * from Test where id = 20  > -1;
-- shows whole table structure

在这个例子之前,我的问题是在那个特定的比较时刻发生了什么。为什么id=20>0和id=20>-1的行为不同。

j7dteeu8

j7dteeu81#

以下是有疑问的问题:

SELECT *
FROM Test
WHERE id = 20 > -1;

上面返回整个表的原因是 WHERE 子句实际上包含一个范围比较,其计算方式如下:

SELECT *
FROM Test
WHERE (id = 20) > -1;

表达式 (id = 20) 将评估为 1 ,如果为真,或 0 ,如果为false。无论哪种情况,0和1都将始终大于 -1 ,因此此查询将始终返回所有记录。

相关问题