為什麼 MySQL 中比較型別不會引發錯誤?


如果你嘗試比較字串和 int,MySQL 不會引發錯誤,因為它會將字串轉換為 int。讓我們先建立一個表 -

mysql> create table DemoTable1852
     (
     Value1 varchar(20),
     Value2 int
     );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable1852 values('1John',1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1852 values('John',1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1852 values('1',1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1852 values('John1',1);
Query OK, 1 row affected (0.00 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select * from DemoTable1852;

這將生成以下輸出 -

+--------+--------+
| Value1 | Value2 |
+--------+--------+
| 1John  |      1 |
| John   |      1 |
| 1      |      1 |
| John1  |      1 |
+--------+--------+
4 rows in set (0.00 sec)

以下是在 MySQL 中比較型別並且不會引發錯誤的查詢 -

mysql> select Value1,Value2, Value1=Value2 as Result from DemoTable1852;

這將生成以下輸出 -

+--------+--------+--------+
| Value1 | Value2 | Result |
+--------+--------+--------+
| 1John  |      1 |      1 |
| John   |      1 |      0 |
| 1      |      1 |      1 |
| John1  |      1 |      0 |
+--------+--------+--------+
4 rows in set, 3 warnings (0.00 sec)

更新時間:2019 年 12 月 26 日

99 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.