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

Truy vấn MySQL đơn tìm giá trị cao nhất và thấp nhất từ hai bảng

Sử dụng MAX(), MIN() kết hợp UNION để gộp dữ liệu hai bảng. Tạo bảng 1:

mysql> CREATE TABLE DemoTable1 (
    UniqueId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    Score1 INT
); Query OK, 0 rows affected (0.76 sec)

Chèn dữ liệu:

mysql> INSERT INTO DemoTable1(Score1) VALUES(56); Query OK, 1 row affected (0.14 sec)
mysql> INSERT INTO DemoTable1(Score1) VALUES(76); Query OK, 1 row affected (0.12 sec)
mysql> INSERT INTO DemoTable1(Score1) VALUES(65); Query OK, 1 row affected (0.09 sec)

Tạo bảng 2:

mysql> CREATE TABLE DemoTable2 (
    UniqueId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    Score2 INT
); Query OK, 0 rows affected (0.93 sec)

Chèn dữ liệu:

mysql> INSERT INTO DemoTable2(Score2) VALUES(67); Query OK, 1 row affected (0.68 sec)
mysql> INSERT INTO DemoTable2(Score2) VALUES(94); Query OK, 1 row affected (0.12 sec)
mysql> INSERT INTO DemoTable2(Score2) VALUES(98); Query OK, 1 row affected (0.08 sec)

Truy vấn gộp hai cột Score, tìm Max và Min:

mysql> SELECT MAX(commonValue) AS Highest_Value, MIN(commonValue) AS Lowest_Value 
FROM (
    SELECT Score1 AS commonValue FROM DemoTable1
    UNION
    SELECT Score2 AS commonValue FROM DemoTable2
) tbl;

Kết quả:

+---------------+--------------+
| Highest_Value | Lowest_Value |
+---------------+--------------+
| 98            | 56           |
+---------------+--------------+
1 row in set (0.04 sec)

Giải thích: UNION gộp hai tập kết quả (loại bỏ trùng lặp), truy vấn ngoài tính Max/Min trên tập gộp.