【问题标题】:I want to understand the execution of the following SQL Query我想了解以下 SQL Query 的执行情况
【发布时间】:2020-02-01 13:33:15
【问题描述】:
create table student(StudentCode varchar,  Marks int);   

insert into student values ('a',100);
insert into student values ('b',100);
insert into student values ('c',100);
insert into student values ('d',90);
insert into student values ('e',90);
insert into student values ('f',80);
insert into student values ('g',70);

SELECT *
FROM student a
WHERE a.StudentCode IN (
        SELECT TOP 1 b.StudentCode
        FROM student b
        WHERE a.marks = b.marks
        );

输出是

StudentCode Marks
1   a   100
2   d   90
3   f   80
4   g   70

为什么每条记录在加入子查询后不重复

【问题讨论】:

    标签: sql sql-server subquery correlated-subquery


    【解决方案1】:

    对于每个 Mark 值,显示一个拥有该 Mark 的学生,即使有更多学生拥有该 Mark 去掉顶部,全部重复:

    select * from student a where a.StudentCode in (select b.StudentCode from student b where a.marks=b.marks);
    

    【讨论】:

      【解决方案2】:

      这是您的查询:

      select s.*
      from student s
      where s.StudentCode in (select top 1 s2.StudentCode
                              from student s2
                              where s2.marks = s.marks
                             );
      

      相关子查询正好返回一行。因此,不需要in。返回的行是具有相同分数的学生的任意行。

      如果只有一个学生具有给定的 marks 值 - 例如 'f''g',则该学生匹配。

      对于其余部分,匹配的学生可能是也可能不是外部查询中的一个引用。因此,子查询会将它们过滤掉。

      如果您删除 top (1),则查询将返回所有学生。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 2016-07-29
        • 2020-08-09
        • 1970-01-01
        • 2020-01-08
        • 1970-01-01
        • 2019-11-23
        相关资源
        最近更新 更多