Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Sử dụng UPDATE với kiểu TINYINT trong MySQL

Giới thiệu

Kiểu dữ liệu TINYINT trong MySQL thường dùng để lưu giá trị boolean (0/1). Bài viết minh họa cách cập nhật cột TINYINT bằng giá trị true/false.

1. Tạo bảng

mysql> create table DemoTable (
    -> EmployeeId int,
    -> isMarried tinyint
    -> ); 
Query OK, 0 rows affected (6.84 sec)

2. Chèn dữ liệu

MySQL cho phép chèn true (→ 1) và false (→ 0) trực tiếp vào cột TINYINT.

mysql> insert into DemoTable values(101,true); 
Query OK, 1 row affected (1.94 sec)
mysql> insert into DemoTable values(102,false); 
Query OK, 1 row affected (0.76 sec)
mysql> insert into DemoTable values(103,true); 
Query OK, 1 row affected (1.14 sec)
mysql> insert into DemoTable values(104,true); 
Query OK, 1 row affected (1.22 sec)

3. Dữ liệu ban đầu

mysql> select *from DemoTable;
+------------+----------+
| EmployeeId | isMarried|
+------------+----------+
|        101 |        1 |
|        102 |        0 |
|        103 |        1 |
|        104 |        1 |
+------------+----------+
4 rows in set (0.00 sec)

4. Cập nhật giá trị

mysql> update DemoTable
    -> set isMarried=false
    -> where EmployeeId=103; 
Query OK, 1 row affected (1.24 sec)
Rows matched: 1 Changed: 1 Warnings: 0

5. Kết quả sau cập nhật

mysql> select *from DemoTable;
+------------+----------+
| EmployeeId | isMarried|
+------------+----------+
|        101 |        1 |
|        102 |        0 |
|        103 |        0 |
|        104 |        1 |
+------------+----------+
4 rows in set (0.00 sec)

Lưu ý quan trọng:

  • TINYINT lưu trữ số nguyên từ -128 đến 127 (hoặc 0-255 nếu UNSIGNED)
  • Giá trị true = 1, false = 0
  • Khi truy xuất, cột sẽ hiển thị số 0/1, không phải chuỗi 'true'/'false'