简体   繁体   中英

How to join two tables without duplicates?

I have an in table that looks like this:

id_in  | date_in   
-------|--------------------------
1      | 2016-04-29 02:00:00

And an out table that looks like this:

id_out    |  date_out
----------|--------------------------
1         | 2016-04-29 03:00:00
2         | 2016-04-29 04:00:00
3         | 2016-04-29 05:00:00

I want to write a query whose output looks like this:

id_in | date_in                     | id_out                     | date_out
------|---------------------------- |----------------------------|---------------------------
1     | 2016-04-29 02:00:00         | 1                          |2016-04-29 03:00:00
NULL  |  NULL                       | 2                          |2016-04-29 04:00:00
NULL  |  NULL                       | 3                          |2016-04-29 05:00:00

You can do this with a left join :

select i.id_in, i.date_in, o.id_out, o.date_out
from outtable o left join
     intable i
     on o.id_in = i.id_out;

Or you can do this with a right join

select i.id_in, i.date_in, o.id_out, o.date_out
from intable i right join
     outtable o
     on o.id_in = i.id_out;

Let's call the table with id_in 'table_in' and the table with id_out 'table_out'

You want to join table_in to table_out. In this case, you want to left join table_in to table_out on the id field. This will ensure you return all records from table_out regardless of whether they have a corresponding record in table_in:

select table_in.id_in, table_in.date_in, table_out.id_out, table_out.date_out
from table_out
left join table_in
on table_out.id_out = table_in.id_in

(Alternatively, you can table_in right join table out for the same results)

If you want all the records from both tables regardless of whether there is a corresponding record in the other, you should use full join .

简单你可以试试这个

select * from table_id i right join table_out o on i.id_in = o.id_out

This query results the same as your need..

SELECT a.id_in, a.date_in, b.id_out, b.date_out
FROM intable AS a RIGHT JOIN
     outtable AS b
     ON a.id_in = b.id_out

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