如何解决这个查询语句?

时间:2019-05-28 15:43:06

标签: sql-server sql-server-2012

请帮我解决此SQL语句。我花了几天时间解决这个问题。

我使用SQL Server 2012。

Level = N'First'-我使用Unicode文本

SELECT ss.id,
       ss.SID,
       CONCAT(CONCAT(ss.Name, ' '), ss.Surname) AS Sname,
       ss.Level,
       pp.PID,
       CONCAT(CONCAT(pp.Name1, ' '), pp.Name2) AS Pname,
       ss.Chk
FROM tb_student1 AS ss,
     tb_parent AS pp
WHERE ss.ParentID = pp.PID
  AND ss.Level = N'First'
  AND ss.Chk = 1
  AND NOT EXISTS (SELECT st.SID
                         FROM (SELECT s.id,
                                      s.SID,
                                      CONCAT(CONCAT(s.Name, ' '), s.Surname) AS Sname,
                                      p.PID,
                                      CONCAT(CONCAT(p.Name1, ' '), p.Name2) AS Pname,
                                      s.Chk
                               FROM tb_student1 AS s,
                                    tb_parent AS p
                               WHERE s.ParentID = p.PID
                                 AND s.Level = N'First'
                                 AND s.Chk = 1) AS st ,
                              (SELECT * FROM tb_New_Reg AS r) AS rnp
                         WHERE st.SID = rnp.SID
                           AND rnp.ClassID = 'C104'
                           AND rnp.Year = '2018-2019'
                           AND rnp.Term = 'Jan'
                           AND rnp.Level = N'First'
                           AND st.Chk = 1);

如果我在这里使用(...和ss.SID不存在...)错误。如果我使用(...并且不存在....)返回null

第一个查询包含11行,子查询包含6行

如何解决?

1 个答案:

答案 0 :(得分:2)

WITH data AS (
    SELECT
        ss.id, ss.SID,
        CONCAT(CONCAT(ss.Name, ' '), ss.Surname) AS Sname,
        ss.Level, pp.PID,
        CONCAT(CONCAT(pp.Name1, ' '), pp.Name2) AS Pname,
        ss.Chk
    FROM tb_student1 AS ss INNER JOIN tb_parent AS pp ON ss.ParentID = pp.PID
    WHERE ss.Level = N'First' AND ss.Chk = 1
)
SELECT * FROM data AS s
WHERE NOT EXISTS (
    SELECT * FROM tb_New_Reg AS rnp
    WHERE s.SID = rnp.SID
        AND rnp.ClassID = 'C104'
        AND rnp.Year = '2018-2019'
        AND rnp.Term = 'Jan'
        AND rnp.Level = N'First'
);

我认为这与您要查找的内容一致。我确实将您的主要查询分解为CTE,以为我会在子查询中复制相同的查询。事实证明,这并不是真正必要的,但我已将其保留。

我想您的尝试失败了,因为当您真正想要将搜索范围缩小到外部查询中匹配的SID时,内部查询正在整个表中进行搜索。您可能会发现查找相关子查询有助于更好地理解该概念。