Vincent Vincent - 6 months ago 12
SQL Question

Converting complex SQL to JOIN

I have the following SQL statement. Which is working okay. Except in some cases the processing of the query takes a lot of time, resulting in a system time out. So I need to convert the statement. Probably with a JOIN.

I can't figure out how to convert this statement:

SELECT table1.id as id,
table1.firstname,
table1.lastname,
table3.name,
table4.name

FROM table1, table2, table3, table4, table5

WHERE table1.id = table2.tabel1id
AND table2.table2id = table3.table2id
AND table3.table3id = table5.table3id
AND table5.somecode = '5'
AND table3.table3id = table4.name
AND table1.firstname LIKE '%John%'

GROUP BY table1.id
ORDER BY table3.name, table1.firstname, table1.lastname


I have the nesting of the tables and I also want to use the results of subqueries in the final SELECT (table3.name and table4.name)

Answer
select t1.id,t1.firstname,t3.name,t4.name 
from table1 as t1 
inner join table2 as t2 on t1.id=t2.tabel1id 
inner join on table3 as t3 on t2.table2id=t3.table2id
inner join on table4 as t4 on t3.table3id=t4.name
inner join on table5 as t5 on t5.table3id=table3.table3id 
where t1.firstname like '%John%' and t5.somecode='5'
group by t1.id
order by t3.name,t1.firstname,t1.lastname
Comments