[英]How to return content of main table in JOIN?
I have table1
and table2
my goal is execute a query that take all data available (matching the code), this is my query actually: 我有
table1
和table2
我的目标是执行一个查询,以获取所有可用数据(与代码匹配),这实际上是我的查询:
SELECT * FROM table1
INNER JOIN table2
ON table1.code = table2.code
All working good, but if for example in the table2
a specific code isn't exists the data of the table1
aren't returned. 一切正常,但是例如在
table2
中不存在特定代码的情况下,不会返回table1
的数据。 An example: 一个例子:
TABLE1 表格1
|CODE|Info|
|R789|Home|
|R788|Away|
TABLE2 表2
|CODE|DESCRIPTION|
|R789| Test
will return only the content of R789
, but I want that also the content of R788
must be returned, of course only the field of table1
'cause in table2
the record doesn't exists. 我将只返回
R789
的内容,但我希望还必须返回R788
的内容,当然只返回table1
的字段,因为table2
的记录不存在。 How can I do that? 我怎样才能做到这一点?
Use a LEFT JOIN
, which will return content from both tables if the "CODE" exists in both, and items from Table1 with NULL
s for items from Table2 if the code doesn't exist there. 使用
LEFT JOIN
,如果两个代码中都存在“ CODE”,则将返回两个表中的内容;如果其中不存在代码,则返回Table1中带有NULL
的表中的内容。
Lots of documentation out there for this. 有关此的大量文档。 Here's one example and another one .
这是一个例子 , 另一个 例子 。
If you want to get all the data from both tables but matching if corresponds, you should use a full outer join: 如果要从两个表中获取所有数据,但要匹配if对应的数据,则应使用完整的外部联接:
select a.*,
b.*
from table1 a
full outer join
table2 b
on a.code=b.code
It will returns something like this: 它将返回如下内容:
|CODE|Info|CODE|DESCRIPTION|
|R789|Home|R789|Test|
|R788|Away|null|null|
Regards 问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.