相关文章推荐
潇洒的茶壶  ·  mysql workbench ...·  8 月前    · 
玩命的松树  ·  java visual ...·  1 年前    · 
睡不着的绿豆  ·  psycopg2 - jihite - 博客园·  2 年前    · 


将一个sql语句的结果作为条件来判断:子查询
-- 子查询的语句,查询的列只允许一个
-- 子查询的语句,如果使用子查询和比较运算符联合使用(=,>,<,<=,>=)必须保证子查询的值不能多于一个
-- 使用 in 关键字 使可以返回多组数据 如果查询不在这里面的数据在 in 前面加上 not 即可
--子查询在where 语句的一般用法:select * from 表1 where 字段1>(子查询)
--我们的查询称为父查询,括号中嵌入的查询称为子查询
update,insert,delete一起使用,语法类似于select语句

联接-合并多个数据表中的列

子查询-将一个查询包含到另一个查询中

IN 子查询后面可跟随返回多条记录的子查询,用于检测某列的值是否在某个范围

--查看表中数据
select * from stuInfo;
select * from stuMarks;
--聚合函数的使用
select count(*) from stuInfo where stuSex='男';
select stuSex,count(*) as '男女的人数'from stuInfo group by stuSex;
--表关联操作
select * from stuInfo a inner join stuMarks b on a.stuNo=b.stuNo;
--查看年龄比“李斯文”大的学员
select * from stuInfo where stuAge>(select stuAge from stuInfo where stuName='李斯文');

--查看性别和“李斯文”一致的学员
select * from stuInfo where stuSex=(select stuSex from stuInfo where stuName='李斯文');
select stuSex from stuInfo where stuName='李斯文';
--查删除别和“李斯文”一致的学员
delete  from stuInfo where stuSex =(select stuSex from stuInfo where stuName='李斯文');
--查询年龄最大的学生信息
select top 1 * from stuInfo order by stuAge desc;
select * from stuInfo where stuAge=(select max(stuAge) from stuInfo );
--查询年龄最小的学生信息
select * from stuInfo where stuAge=(select min(stuAge) from stuInfo );
--查询笔试成绩成绩最高的学生
select * from stuInfo where stuNo=(select top 1 stuNo from stuMarks order by writtenExam desc);
select  top 1 a.stuNo,a.stuName,b.writtenExam  from stuInfo a inner join stuMarks b on a.stuNo=b.stuNo order by writtenExam desc;
--查询笔试成绩大于全班笔试平均成绩的学生记录
select * from stuInfo a inner join stuMarks b on a.stuNo=b.stuNo where writtenExam>(select avg(writtenExam) from stuMarks);
--查询笔试成绩在70分以上的学生信息(禁止联表)

select * from stuInfo where stuNo in(select stuNo from stuMarks where writtenExam>70);
--查看那些人没有考试
select * from stuInfo where stuNo not in (select stuNo from stuMarks);
select * from stuInfo a left join stuMarks b on a.stuNo=b.stuNo where writtenExam is null;

WFE_FlowRecord 中 WFE_FRCode为主键,WFE_PFRCode为父 的主键 现在想查询某个子 的所有父 的数据,且父 的标志位为WFE_FRSubFlow = 'F'  查询语句如下: with cte AS select WFE_PFRCode,WFE_FRSubFlow,WFE_FRCode,0 as lvl from WFE --查询钱包里金额大于30000 select * from Users where exists (select User_ID from Wallets where Money > 30000 and User_ID = Users.ID) select * from Users where ID in (select U...
SQL Server 中的 子查询 是指在一个查询语句中嵌套 使用 另一个查询语句。 子查询 可以作为主查询的一部分,用于获取更具体的数据或进行进一步的筛选和计算。 下面是一个示例,展示如何在 SQL Server 使用 子查询 : ``` sql SELECT column1, column2 FROM table1 WHERE column1 IN (SELECT column1 FROM table2 WHERE column2 = 'value') 在上面的示例中,主查询从table1 中选择column1和column2列的数据。 子查询 被嵌套在WHERE子句中,用于从table2 中选择满足条件column2 = 'value'的column1列的数据。主查询将返回满足 子查询 条件的结果。 子查询 也可以用于其他操作,例如计算聚合 函数 、连接多个 等。在 使用 子查询 时,需要注意优化查询以提高性能,并确保正确 使用 子查询 的结果。 希望这个简单的示例对您有所帮助!如果您有更多关于 SQL Server 子查询 的问题,请随时提问。