在这里插入代码片—
1.with语法
with语句是一种在sql中常用的语法,用于创建临时表或视图,以便在后续的查询中使用。它可以简化复杂查询的编写,并提高查询性能。以下是一些with语句的示例:
1.1 创建临时表
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语句递归查询
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语句中使用多个查询
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语句来简化多个查询的编写,并提高查询性能。
用例
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
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 相等的记录,
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;
发表评论