一个MySQL查询来查找两个表中的最高价和最低价?

要从两个表中找到最高和最低值,请使用MAX()和MIN()。由于要从两个表中显示结果,因此需要使用UNION。让我们首先创建一个表-

create table DemoTable1
(
   UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Score1 int
);

使用插入命令在表中插入一些记录-

insert into DemoTable1(Score1) values(56);
insert into DemoTable1(Score1) values(76);
insert into DemoTable1(Score1) values(65);

使用select语句显示表中的所有记录-

select *from DemoTable1;

这将产生以下输出-

+----------+--------+
| UniqueId | Score1 |
+----------+--------+
|        1 |     56 |
|        2 |     76 |
|        3 |     65 |
+----------+--------+
3 rows in set (0.00 sec)

以下是创建第二个表的查询-

create table DemoTable2
(
   UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Score2 int
);

使用插入命令在表中插入一些记录-

insert into DemoTable2(Score2) values(67);
insert into DemoTable2(Score2) values(94);
insert into DemoTable2(Score2) values(98);

使用select语句显示表中的所有记录-

select *from DemoTable2;

这将产生以下输出-

+----------+--------+
| UniqueId | Score2 |
+----------+--------+
|        1 |     67 |
|        2 |     94 |
|        3 |     98 |
+----------+--------+
3 rows in set (0.00 sec)

以下是在2个表中查找最高和最低的查询-

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;

这将产生以下输出-

+---------------+--------------+
| Highest_Value | Lowest_Value |
+---------------+--------------+
|            98 |           56 |
+---------------+--------------+
1 row in set (0.04 sec)
猜你喜欢