Display two different columns from two different tables with ORDER BY?

MySQLMySQLi Database

For this, you can use UNION along with the ORDER BY clause. Let us first create a table −

mysql> create table DemoTable1
(
   Amount int
);
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(234);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1 values(567);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values(134);
Query OK, 1 row affected (0.43 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+--------+
| Amount |
+--------+
|    234 |
|    567 |
|    134 |
+--------+
3 rows in set (0.00 sec)

Here is the query to create the second table −

mysql> create table DemoTable2
(
   Price int
);
Query OK, 0 rows affected (0.73 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(134);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2 values(775);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable2 values(121);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable2 values(882);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+-------+
| Price |
+-------+
|   134 |
|   775 |
|   121 |
|   882 |
+-------+
4 rows in set (0.00 sec)

Following is the query to display two different columns from two different tables with ORDER BY −

mysql> select distinct Amount from DemoTable1
   UNION
   select distinct Price from DemoTable2
   order by Amount;

This will produce the following output −

+--------+
| Amount |
+--------+
|    121 |
|    134 |
|    234 |
|    567 |
|    775 |
|    882 |
+--------+
6 rows in set (0.00 sec)
raja
Published on 01-Oct-2019 08:48:51
Advertisements