简体   繁体   中英

union of left and right joins sql

I am trying to wrap my head around union of left and right join but I just can not seem to do it as the tables have different values in them as such:

Table1  
table1ID, clientNo, clientName, ClientCity  
Table2  
table2ID, RoomNo, clientNo, DateTo, DateFrom

What I need to do is join the 2 to get the following values:
clientName, clientCity, roomNo, dateFrom, DateTo

I have tried multiple ways to do this and as there is only 2 fields in table1 I get errors all the time and it will not accept NULL as a select field. Much appreciated :)

Thanks

Rob

As I see there is a clientNo in both tables, so you must join on that field.

SELECT t1.clientMame,
       t1.clientCity,
       t2.roomNo,
       t2.dateFrom,
       t2.dateTo
FROM Table1 t1
INNER JOIN Table t2
    ON t1.clientNo = t2.clientNo

INNER JOIN will bring you only rows that are in both tables, if you want to show clients without rooms use LEFT JOIN.

Here is a nice picture that illustrates joins in SQL:

联接的插图

Just try this

select clientNo,clientName,clientCity, RoomNo as "",DateTo as "", DateFrom as "" from Table1
union 
select clientNo,clientName as "",clientCity as "",RoomNo,DateTo,DateFrom from Table2

If you want to do a union you must have same count of column otherwise you have to declare and make the field value as empty or null, You should have same order of the column set in your select query of the both table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM