简体   繁体   English

Mysql:左连接和内连接子查询

[英]Mysql : Left Join and Inner Join in a subquery

I have 3 tables that i have left joined but I would like to add a field from the table 3 which is inner joined with table 2. 我有3张桌子,我已经离开了,但是我想从表格3中添加一个字段,它与表格2连接在一起。

Table1
id
name
surname
table2_fk

Table2
id
entry_name
entry_code
table3_fk

Table3
id
type_name
type_desc

SELECT `Name`, `Type Description`
(SELECT
Table1.name AS `Name`,
Table1.surname AS `Surname`,
t2.entry_name AS `Entry`,
t2.entry_code AS `Entry Code`,
t3.type_name AS `Type Name`,
t3.type_desc AS `Type Description`

FROM Table1
LEFT JOIN table2 AS t2 ON Table1.table2_fk = t2.id
LEFT JOIN table3 AS t3 ON Table2.table3_fk = t3.id
) as subquery

My desired outcome is to have t2 inner join t3 and get field from table 1 and table 3 我期望的结果是从表1和表3获得t2内连接t3和get字段

Based on my subquery I would like the Name and Type Description to show 基于我的子查询,我希望显示NameType Description

If you want to INNER JOIN tables table2 and table3 and then LEFT JOIN to table1 then do this: 如果你想INNER JOINtable2table3 ,然后LEFT JOINtable1那么这样做:

SELECT t1.name, t.type_desc AS `Type Description`
FROM Table1 AS t1
LEFT JOIN (
   SELECT t2.id, t3.type_desc
   FROM table2 AS t2 
   INNER JOIN table3 AS t3 ON t2.table3_fk = t3.id
) AS t ON t1.table2_fk = t2.id

But this could be perhaps expressed just as: 但这可能表达为:

SELECT t1.name, t3.type_desc AS `Type Description`
FROM Table1 AS t1
LEFT JOIN table2 AS t2 ON t1.table2_fk = t2.id
LEFT JOIN table3 AS t3 ON t2.table3_fk = t3.id

I presume you are trying to left join table1 with the result of inner join between table2 and table3 我假设你试图将table1与table2和table3之间的内连接结果保持连接

select t1.name, t_res.type_desc from table1 t_1 
left join (
   select t_2.id, t_3.type_desc from table2 t_2 
   inner join table3 t_3 on t_2.table3_fk = t_3.id
) as t_res on t_1.table2_fk = t_2.id

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

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