2016-02-15 138 views
4

我有,我已经离开加盟,但我想从表3是内与表连接添加一个字段3个表2.MySQL的:左连接和内部连接在一个子查询

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 

我所需结果是有T2内连接T3,并从表1和表让现场3

根据我的子查询我想NameType Description显示

+0

请包括示例输入和输出,以便我们不hav e推测。 –

+0

你是什么意思?你想实现什么 – sagi

+0

目前你的查询有什么问题? – shmosel

回答

1

如果你想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 
+0

我不认为第二个查询是相同的。如果表2中有一行匹配表1但不匹配表3,该怎么办?你的第一个查询将排除它,但不是你的第二个查询。 – shmosel

+0

@shmosel这是正确的,第二个查询*可能会返回比第一个更多的记录。这取决于实际的数据。 –

0

我相信你正在尝试左连接表1与内连接的结果表2和表3之间

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