当前位置: 代码网 > it编程>数据库>MsSqlserver > SQL常用语法( WITH 语句)

SQL常用语法( WITH 语句)

2024年08月06日 MsSqlserver 我要评论
WITH语句

在这里插入代码片—


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;

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com