Select the minimum value from the maximum values of two tables with a single MySQL query?

MySQLMySQLi Database

For this, you can use UNION in MySQL. Let us first create a table −

mysql> create table DemoTable1
   -> (
   -> Value int
   -> )
   -> ;
Query OK, 0 rows affected (0.48 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(60);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1 values(78);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values(57);
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1;

This will produce the following output

+-------+
| Value |
+-------+
|    60 |
|    78 |
|    57 |
+-------+
3 rows in set (0.00 sec)

Here is the query to create second −

mysql> create table DemoTable2
    -> (
    -> Value int
    -> );
Query OK, 0 rows affected (0.48 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(90) ;
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2 values(67) ;
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable2;

This will produce the following output

+-------+
| Value |
+-------+
|    90 |
|    67 |
+-------+
2 rows in set (0.00 sec)

Here is the query to select the minimum value from the maximum value of two tables −

mysql> select min(tbl.Value) as Value
   -> from
   -> (
   -> select max(Value) as Value from DemoTable1608
   -> union
   -> select max(Value) as Value from DemoTable1609
   -> ) as tbl;

This will produce the following output

+-------+
| Value |
+-------+
|    78 |
+-------+
1 row in set (0.04 sec)
raja
Published on 17-Dec-2019 10:28:03
Advertisements