To merge selects together, you need to use GROUP BY clause. To understand the concept, let us create a table. The query to create a table is as follows −
mysql> create table MergingSelectDemo -> ( -> RoomServicesId int, -> RoomId int, -> ServiceId int -> ); Query OK, 0 rows affected (1.98 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into MergingSelectDemo values(10,10,10); Query OK, 1 row affected (0.29 sec) mysql> insert into MergingSelectDemo values(20,10,20); Query OK, 1 row affected (0.22 sec) mysql> insert into MergingSelectDemo values(30,10,30); Query OK, 1 row affected (0.14 sec) mysql> insert into MergingSelectDemo values(50,10,50); Query OK, 1 row affected (0.19 sec) mysql> insert into MergingSelectDemo values(110,20,20); Query OK, 1 row affected (0.14 sec) mysql> insert into MergingSelectDemo values(120,20,30); Query OK, 1 row affected (0.37 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from MergingSelectDemo;
The following is the output −
+----------------+--------+-----------+ | RoomServicesId | RoomId | ServiceId | +----------------+--------+-----------+ | 10 | 10 | 10 | | 20 | 10 | 20 | | 30 | 10 | 30 | | 50 | 10 | 50 | | 110 | 20 | 20 | | 120 | 20 | 30 | +----------------+--------+-----------+ 6 rows in set (0.00 sec)
Here is the query to merge select together −
mysql> select RoomId from MergingSelectDemo -> where ServiceId IN(10,20,30) -> group by RoomId -> HAVING COUNT(*)=3;
The following is the output −
+--------+ | RoomId | +--------+ | 10 | +--------+ 1 row in set (0.15 sec)