我需要T-SQL select语句的帮助。它适用于SQL Server 2014
我有3张桌子。
表1(Courses
)有2列我需要查询 - AllowReEnrollment
和ReEnrollAutomatically
表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我花了一天时间试图解决这个问题。我该如何撰写此查询?
答案 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)