将复杂的SQL转换为JOIN

时间:2014-01-17 08:46:24

标签: mysql sql sql-server subquery inner-join

我有以下SQL语句。哪个工作正常。除了在某些情况下,查询的处理需要花费大量时间,导致系统超时。所以我需要转换声明。可能还有JOIN。

我无法弄清楚如何转换此声明:

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

我有表的嵌套,我也想在最终的SELECT(table3.name和table4.name)中使用子查询的结果

3 个答案:

答案 0 :(得分:0)

您已经有JOIN,但是您使用隐式版本(FROM中的逗号分隔表列表以及WHERE中的join-conditions)而不是显式(JOIN加ON)。

所以重写不应该提高性能(否则MySQL比我想象的更糟糕)。

您最好检查是否创建了所有必要的索引。

答案 1 :(得分:0)

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

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

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

Read Here有关sql server JOIN语法的更多信息

答案 2 :(得分:0)

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