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

时间:2016-02-15 07:52:10

标签: mysql join

我有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

我希望的结果是从表1和表3获得t2内连接t3和get字段

根据我的子查询,我希望显示NameType Description

2 个答案:

答案 0 :(得分:2)

如果您想要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

但这可能表达为:

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

答案 1 :(得分:1)

我认为你试图将table2与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