MySQL 中 IS TRUE 和 =True 查詢結果不一致的原因是什么?

MySQL 中 IS TRUE 和 =True 查詢結果不一致的原因是什么?

mysql 中 is true 和 =true 結果不一致的原因

mysql 中查詢數據時,使用 is true 和 =true 作為條件會導致不同的結果。這是因為這兩個操作具有不同的語義:

  • = 執行的是數值比較。true 在 mysql 中表示為 1,但 is_deleted 列是一個 tinyint(1) 類型,它的取值范圍為 0-255。因此,=true 實際上是將 is_deleted 與 1 進行比較。
  • is true 執行的是真假判斷。在 mysql 中,非零值都表示 true,而 0 表示 false。因此,is true 將 is_deleted 為非零(即不等于 0)的記錄視為 true。

示例

已知表結構如下:

create table user (   id int not null auto_increment,   is_deleted tinyint(1) not null default 0,   primary key (id) );

插入的示例數據:

insert into user (is_deleted) values (127); insert into user (is_deleted) values (0);

查詢結果

執行以下查詢語句:

select * from `user` where is_deleted is true;

結果:

+----+------------+ | id  | is_deleted | +----+------------+ | 1   | 127        | +----+------------+

執行以下查詢語句:

select * from `user` where is_deleted = true;

結果:

空集

可見,使用 is true 查詢到了 is_deleted 為 127(非 0)的記錄,而使用 =true 未查詢到任何記錄。

? 版權聲明
THE END
喜歡就支持一下吧
點贊13 分享