添加别名的重要性
-- ============================================= -- Author: <Author,,CC> -- Create date: <Create Date,, 2014-06-29 12:25:20.010> -- Description: <Description,,加别名的重要性> -- Environment: <Version,, Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64))> -- ============================================= use test go create table t1( id int , id1 int ) create table t2( id11 int, id2 int ) insert into t1(id ,id1) select 1,2 union all select 2,3 union all select 3,4 union all select 4,5 union all select 5,5 insert into t2(id11,id2) select 1,2 union all select 2,3 create table t3( id int, id2 int ) insert into t3(id,id2) select 1,2 union all select 2,3 -- 1.查询t1表中的id在t3中的记录,没有别名,记录正确 select * from t1 a where id in (select id from t3 b) --2. 假如in的内查询中不存在外查询的列 select * from t1 a where id in (select id from t2 b) /* 此时我们可以看到语句并没有错,而是会去寻找t1中的数据,语句结果同下面的查询效果: select * from t1 a where id in (select a.id from t2) 其实是内查询不存在,所以结果就自己去寻找外面的查询 */ --3. 我们把内表加上别名,此时才是我们要的结果,并且提示报错 select * from t1 a where id in (select b.id from t2 b) --删除t2中的数据,再测试一下 truncate table t2 --3. t2中没有数据,此时则不会往外层寻找 select * from t1 a where id in (select a.id from t2) drop table t1,t2,t3
以上结果只是查询,若换为删除出现这种情况则可能会把外表整个的数据删除掉,造成不能想象的问题,所以在允许的情况下尽量还是要把别名加上.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单