简体   繁体   English

将复杂的SQL转换为JOIN

[英]Converting complex SQL to JOIN

I have the following SQL statement. 我有以下SQL语句。 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. 可能与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) 我有表的嵌套,我也想在最终的SELECT(table3.name和table4.name)中使用子查询的结果

You already have JOINs, but you use the implicit version (comma-delimited table list in FROM plus join-conditions in WHERE) instead of the explicit (JOIN plus ON). 您已经有JOIN,但是使用隐式版本(WROME中的逗号分隔表列表加上WHERE中的联接条件)而不是显式版本(JOIN加ON)。

So rewriting should not improve performance (otherwise MySQL is more crappy than I thought). 因此,重写不应提高性能(否则MySQL比我想象的要糟糕得多)。

You should better check if you created all neccessary indexes. 您最好检查是否创建了所有必要的索引。

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 for more information about sql server JOIN syntax 在这里阅读有关sql server JOIN语法的更多信息

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM