代码示例: 示例1: 减少子查询数量 SELECT column1, (SELECT MAX(column2) FROM table2 WHERE table2.column3 = table1.column3) as max_column2 FROM table1
重写后的查询: SELECT table1.column1, MAX(table2.column2) as max_column2 FROM table1 JOIN table2 ON table2.column3 = table1.column3 GROUP BY table1.column1
示例2:优化子查询性能 SELECT column1, (SELECT COUNT(column2) FROM table2 WHERE table2.column3 = table1.column3) as count_column2, (SELECT AVG(column2) FROM table2 WHERE table2.column3 = table1.column3) as avg_column2 FROM table1
重写后的查询: SELECT table1.column1, COUNT(table2.column2) as count_column2, AVG(table2.column2) as avg_column2 FROM table1 JOIN table2 ON table2.column3 = table1.column3 GROUP BY table1.column1