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

Cách chọn phạm vi giá trị cụ thể trong bảng MySQL?

Sử dụng mệnh đề WHERE với các toán tử so sánh (>=, <=, BETWEEN) kết hợp logic AND/OR.

Tạo bảng khách hàng

mysql> CREATE TABLE DemoTable (
    -> CustomerId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> CustomerName VARCHAR(200),
    -> CustomerAge INT,
    -> IsRegularCustomer BOOL
    -> );

Chèn dữ liệu

mysql> INSERT INTO DemoTable(CustomerName, CustomerAge, IsRegularCustomer) VALUES('Chris', 24, TRUE);
mysql> INSERT INTO DemoTable(CustomerName, CustomerAge, IsRegularCustomer) VALUES('Robert', 26, FALSE);
mysql> INSERT INTO DemoTable(CustomerName, CustomerAge, IsRegularCustomer) VALUES('Mike', 27, FALSE);
mysql> INSERT INTO DemoTable(CustomerName, CustomerAge, IsRegularCustomer) VALUES('Larry', 22, TRUE);
mysql> INSERT INTO DemoTable(CustomerName, CustomerAge, IsRegularCustomer) VALUES('Sam', 30, TRUE);
mysql> INSERT INTO DemoTable(CustomerName, CustomerAge, IsRegularCustomer) VALUES('Carol', 26, TRUE);

Xem dữ liệu

mysql> SELECT * FROM DemoTable;
+------------+--------------+-------------+-------------------+
| CustomerId | CustomerName | CustomerAge | IsRegularCustomer |
+------------+--------------+-------------+-------------------+
| 1          | Chris        | 24          | 1                 |
| 2          | Robert       | 26          | 0                 |
| 3          | Mike         | 27          | 0                 |
| 4          | Larry        | 22          | 1                 |
| 5          | Sam          | 30          | 1                 |
| 6          | Carol        | 26          | 1                 |
+------------+--------------+-------------+-------------------+

Lọc: Khách quen (1) TUỔI 24-27

mysql> SELECT CustomerId, CustomerName, CustomerAge, IsRegularCustomer 
    -> FROM DemoTable 
    -> WHERE IsRegularCustomer = TRUE 
    ->   AND CustomerAge >= 24 
    ->   AND CustomerAge <= 27;
+------------+--------------+-------------+-------------------+
| CustomerId | CustomerName | CustomerAge | IsRegularCustomer |
+------------+--------------+-------------+-------------------+
| 1          | Chris        | 24          | 1                 |
| 6          | Carol        | 26          | 1                 |
+------------+--------------+-------------+-------------------+

Cách viết tương đương

-- Dùng BETWEEN (kể cả đầu cuối)
WHERE IsRegularCustomer AND CustomerAge BETWEEN 24 AND 27

-- Dùng IN cho giá trị rời rạc
WHERE IsRegularCustomer AND CustomerAge IN (24, 25, 26, 27)

Mẹo hiệu năng

  • Đặt điều kiện lọc mạnh (selectivity cao) lên đầu: IsRegularCustomer = TRUE trước
  • Tạo composite index: INDEX idx_regular_age (IsRegularCustomer, CustomerAge)
  • Tránh function trên cột: WHERE YEAR(birth) = 1990 → không dùng index. Dùng WHERE birth >= '1990-01-01' AND birth < '1991-01-01'