简体   繁体   English

使用连接的SQL请求

[英]SQL request using join

I have 2 tables: 我有2张桌子:
circuit(id_circuit, distance)
and
circuit_langue(id_circuit_language, #id_circuit, language, title) . circuit_langue(id_circuit_language, #id_circuit, language, title)

if I do a join between circuit and circuit_langue , and it's possible that some objects from circuit don't have a circuit_langue, 如果我在circuitcircuit_langue之间进行join ,并且有可能来自circuit的某些对象没有circuit_langue,

what i have to do if I want to recuperate objects without circuit_langue ? 如果我想调理没有circuit_langue的对象该怎么办?

By default, the JOIN ( INNER JOIN ) recovers rows that match on both tables. 默认情况下, JOININNER JOIN )恢复在两个表上都匹配的行。

If you want to recover both the objects with and without a circuit_langue associated you can use a LEFT OUTER JOIN : 如果要同时恢复带有和不具有circuit_langue的对象,则可以使用LEFT OUTER JOIN

SELECT * FROM circuit c LEFT OUTER JOIN circuit_langue cl
ON c.id_circuit = cl.id_circuit

You most likely did INNER JOIN which shows only those records that have a matching row from both sides of the join (tables in this example). 您极有可能执行了INNER JOIN ,该操作仅显示那些在连接的两边都具有匹配行的记录(在此示例中为表)。

You need a LEFT JOIN to view all circuits even if there is not circuit_langue row associated with it: 即使没有与之关联的circuit_langue行,您也需要LEFT JOIN来查看所有电路:

select *
from circuit c
left join circuit_langue cl on
  c.id_circuit = cl.id_circuit

If you only need to display records that don't have a corresponding row in langue table you could add a WHERE condition to above query: 如果只需要显示在语言表中没有对应行的记录,则可以在上述查询中添加WHERE条件:

select *
from circuit c
left join circuit_langue cl on
  c.id_circuit = cl.id_circuit
where cl.id_circuit is null

There are four main kinds of joins : 联接主要有四种:

  • inner join (which is the default) 内部联接(默认)
  • left outer join 左外连接
  • right outer join 右外连接
  • full outer join 完全外部联接

You've used the INNER JOIN which only returns the matched values in both tables, while you actually need a LEFT OUTER JOIN which returns all rows from the left table, even if there are no matches in the right table. 您已经使用了INNER JOIN ,它只返回两个表中的匹配值,而实际上您需要一个LEFT OUTER JOIN ,它返回左表中的所有行,即使右表中没有匹配项。

For reference, the left table is the first one after the FROM keyword. 作为参考,左表是FROM关键字之后的第一个表。

For further knowledge: 有关更多知识:

  • RIGHT OUTER JOIN : is exactly the opposite of LEFT OUTER JOIN . RIGHT OUTER JOIN :与LEFT OUTER JOIN正好相反。
  • FULL OUTER JOIN :returns rows when there is a match in either one of the tables. FULL OUTER JOIN :当任一表中有匹配项时,返回行。

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

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