Mysql: Left Join and Inner Join the Subquery

I have 3 tables that I have left, but I would like to add a field from table 3, which is internally connected to table 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 result is to have t2 inner join t3 and get the field from table 1 and table 3

As I would like depending on my subquery to Nameand Type Descriptiondisplayed

+4
source share
2 answers

If you want INNER JOINtables table2and table3then LEFT JOIN- table1do the following:

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 can be expressed in the same way 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
+1
source

, join table1 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
0

Source: https://habr.com/ru/post/1628791/


All Articles