A single MySQL select query on two tables is possible?

MySQLMySQLi Database

Yes, it is possible. Following is the syntax −

select * from yourTableName1,yourTableName2;

Let us first create a table −

mysql> create table DemoTable1
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY
   -> );
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(),(),();
Query OK, 3 rows affected (0.14 sec)
Records: 3  Duplicates: 0  Warnings: 0

Display all records from the table using select statement −

mysql> select * from DemoTable1;

This will produce the following output −

+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
+----+
3 rows in set (0.00 sec)

Here is the query to create second table −

mysql> create table DemoTable2
   -> (
   -> FirstName varchar(10)
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values('Chris'),('David'),('Sam');
Query OK, 3 rows affected (0.10 sec)
Records: 3  Duplicates: 0  Warnings: 0

Display all records from the table using select statement −

mysql> select * from DemoTable2;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| Chris     |
| David     |
| Sam       |
+-----------+
3 rows in set (0.00 sec)

Following is the query to perform select query on two tables −

mysql> select Id,FirstName from DemoTable1,DemoTable2;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | Chris     |
|  2 | Chris     |
|  3 | Chris     |
|  1 | David     |
|  2 | David     |
|  3 | David     |
|  1 | Sam       |
|  2 | Sam       |
|  3 | Sam       |
+----+-----------+
9 rows in set (0.00 sec)
raja
Published on 10-Dec-2019 12:16:43
Advertisements