简体   繁体   English

如何连接两个没有重复的表?

[英]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 :您可以使用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或者你可以通过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'让我们调用带有id_in 'table_in' 的表和带有id_out 'table_out' 的表

You want to join table_in to table_out.您想将 table_in连接到 table_out。 In this case, you want to left join table_in to table_out on the id field.在这种情况下,您希望在id字段上将 table_in连接到 table_out。 This will ensure you return all records from table_out regardless of whether they have a corresponding record in table_in:这将确保您从 table_out 返回所有记录,而不管它们在 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) (或者,您可以table_in right join table out以获得相同的结果)

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 .如果你想要两个表中的所有记录,而不管另一个中是否有相应的记录,你应该使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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