1.WITH语法
WITH语句是一种在SQL中常用的语法,用于创建临时表或视图,以便在后续的查询中使用。它可以简化复杂查询的编写,并提高查询性能。以下是一些WITH语句的示例:
1.1 创建临时表
1 2 3 4 5 6 7 8 9 |
WITH temp_table AS ( SELECT column1, column2 FROM some_table WHERE column3 = 'value' ) SELECT * FROM temp_table |
这个WITH语句创建了一个名为temp_table的临时表,其中包含符合条件column3 = ‘value’的some_table表中的column1和column2列。在后续的查询中,可以使用temp_table来引用这些数据。
1.2 用WITH语句递归查询
1 2 3 4 5 6 7 8 9 10 11 12 |
WITH recursive_query AS ( SELECT start_id, end_id, distance FROM some_table WHERE start_id = 1 UNION ALL SELECT r.start_id, t.end_id, r.distance + t.distance FROM recursive_query r JOIN some_table t ON r.end_id = t.start_id ) SELECT * FROM recursive_query |
这个WITH语句使用递归查询来查找从start_id = 1开始的所有路径,并计算它们的距离。在第一部分中,查询从some_table表中选择所有起点为1的路径。在第二部分中,使用UNION ALL操作符来将递归查询的结果与some_table表中的记录连接起来,以查找从起点到终点的路径,并计算它们的距离。这样,可以使用WITH语句来创建一个递归查询,从而简化代码。
1.3在WITH语句中使用多个查询
1 2 3 4 5 6 7 8 9 10 11 12 13 |
WITH temp_table1 AS ( SELECT column1, column2 FROM some_table WHERE column3 = 'value' ), temp_table2 AS ( SELECT column4, column5 FROM another_table WHERE column6 = 'value' ) SELECT * FROM temp_table1 JOIN temp_table2 ON temp_table1.column1 = temp_table2.column4 |
这个WITH语句使用多个查询来创建两个临时表temp_table1和temp_table2。在后续的查询中,使用这些临时表来连接some_table和another_table表,以查找符合条件的记录。这样,可以使用WITH语句来简化多个查询的编写,并提高查询性能。
用例
1 2 3 4 5 6 7 8 9 10 11 12 13 |
WITH w1 AS ( select name, value from diction where code = 's_model' ), w2 AS ( select name,value from diction where code = 'd_model' ), w3 AS ( select project_name,id from project ) select w3.project_name, t1.device_name, t1.device_sn, t1.update_time,t1.device_model,t1.device_type from device t1 left join project_device pd on t1.id = pd.device_id join w3 on w3.id = pd.project_id where t1.device_type in (1,2); |
获取t1.device_type为1,t1.device_mode与w1的value相等获取w1的name值该如何编写sql
1 2 3 4 5 6 7 8 |
WITH w1 AS ( SELECT name, value FROM diction WHERE code = 's_model' ) SELECT w1.name, t1.device_type, t1.device_model FROM device t1 JOIN w1 ON t1.device_model = w1.value WHERE t1.device_type = 1; |
获取 t1.device_type 为 1 且 t1.device_model 与 w1 的 value 相等的记录,t1.device_type 为 2且 t1.device_model 与 w2 的 value 相等的记录,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
WITH w1 AS ( SELECT name, value FROM diction WHERE code = 's_model' ), w2 AS ( SELECT name, value FROM diction WHERE code = 'd_model' ) SELECT w1.name, t1.device_type, t1.device_model FROM device t1 JOIN w1 ON t1.device_model = w1.value WHERE t1.device_type = 1 UNION SELECT w2.name, t1.device_type, t1.device_model FROM device t1 JOIN w2 ON t1.device_model = w2.value WHERE t1.device_type = 2; |
浏览量: 3