Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL compare two tables with common id

Tags:

sql

compare

Given the following tables stored in SQL database

Table person

id   username   phone   
1    james      555-666-777
2    gabriel    666-555-777
3    Lucas      222-888-999
4    Marta      555-444-777

Table room_booking

id   person_id    room     time
1    2            A2       13:00
2    4            B5       09:00
3    1            C1       20:00

By only getting the room_booking id number 2 I would like the output to be:

Output table

id   username   phone 
4    Marta      555-444-777

I know INNER JOIN can do the job but I got fields from the table room_booking included with SELECT *.

like image 419
Alfonso Fernandez-Ocampo Avatar asked Feb 22 '26 04:02

Alfonso Fernandez-Ocampo


1 Answers

As others have said, the answer is to not include the unwanted columns. Since you want all of the columns from one table, and none of the columns from the other table, the solution is to use person.*

Select distinct p.*
from person p
   Inner join room_booking r
      On r.person_id = p.id

I include the distinct because given your structure, you're likely to have more than one booking per person eventually.

Alternate syntax for achieving the same goal...

/*using sub select*/
Select * from person where id in (select person_id from room_booking);

 /*using cte, distinct and inner join*/
 ; pids as(select distinct person_id from room_booking)
 Select person.*
 from pids 
   Inner join person on person_id = id;

 /*using cte and subquery with explicit column list */
; pids as(select person_id from room_booking)
Select id, username, phone
from person 
Where id in (select person_id from pids) 
like image 110
jmoreno Avatar answered Feb 23 '26 18:02

jmoreno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!