子查询的T-SQL错误

时间:2016-02-23 02:16:59

标签: sql-server tsql

我需要T-SQL select语句的帮助。它适用于SQL Server 2014

我有3张桌子。

  • 表1(Courses)有2列我需要查询 - AllowReEnrollmentReEnrollAutomatically

  • 表2(CourseEnrollments)有一个CourseId列,它是Id表的Courses的外键。 Courses可以有多个注册。

  • 表3(Jobs)有一个名为Arguments的列,其中包含Json数据,其中一个值为EnrollmentId {"EnrollmentId":{ENROLLMENT_ID_GUID}},即{{1}来自Id

我需要检查“作业”表格,以确定是否为其CourseEnrollments CourseEnrollment已关闭Course标记的AllowReEnroll计划了任何作业,但ReEnrollAutomatically }标志已打开。

这就是我一直在尝试的

SELECT
    *
FROM
    Jobs
WHERE
    Arguments LIKE '%' + (
        SELECT
            CONVERT( nvarchar(50), Id )
        FROM
            CourseEnrollments
        WHERE
            CourseId IN (
                SELECT
                    Id
                FROM
                    Courses
                WHERE
                    AllowReEnroll = 0
                    AND
                    ReEnrollAutomatically = 1
            )
    ) +'%'

我可以查询CourseEnrollments表,以获取CourseEnrollments的所有ID,其中相应地设置了课程的标志

SELECT
    *
FROM
    CourseEnrollments
WHERE
    CourseId IN (
        SELECT
            Id
        FROM
            Courses
        WHERE
            AllowReEnroll = 0
            AND
            ReEnrollAutomatically = 1
    )

但是当我尝试将其用作子查询时,我收到以下错误:

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。'

不是dba我花了一天时间试图解决这个问题。我该如何撰写此查询?

1 个答案:

答案 0 :(得分:3)

使用EXISTS/Join执行此操作

使用EXISTS

SELECT *
FROM   Jobs j
WHERE  EXISTS (SELECT 1
               FROM   CourseEnrollments c
               WHERE  c.CourseId IN (SELECT Id
                                     FROM   Courses
                                     WHERE  AllowReEnroll = 0
                                            AND ReEnrollAutomatically = 1)
                      AND j.Arguments LIKE '%' + CONVERT(NVARCHAR(50), c.Id) + '%') 

使用INNER JOIN

SELECT j.*
FROM   Jobs j
       JOIN CourseEnrollments c
         ON j.Arguments LIKE '%' + CONVERT(NVARCHAR(50), c.Id) + '%'
WHERE  c.CourseId IN (SELECT Id
                      FROM   Courses
                      WHERE  AllowReEnroll = 0
                             AND ReEnrollAutomatically = 1)