如何为以下脚本实现Join,以避免嵌套脚本

时间:2015-03-03 09:22:38

标签: mysql sql

SELECT UserDCID AS UserDCCompForDelCount1
FROM CDICentral.dbo.UserDCComponent AS udc
WHERE(
    UserDCID IN(
        SELECT UserDCID FROM CDICentral.dbo.UserDC AS ud WHERE (
            UserID NOT IN(
                SELECT UserID FROM CVPLocal.dbo.CSWSecurity AS cs
            )
        )
    )
)

3 个答案:

答案 0 :(得分:0)

试试这个SQL查询

SELECT UserDCID AS UserDCCompForDelCount1 
FROM CDICentral.dbo.UserDCComponent AS udc 
INNER JOIN CDICentral.dbo.UserDC AS ud ON udc.UserDCID=ud.UserDCID
INNER JOIN CVPLocal.dbo.CSWSecurity AS cs ON ud.UserDCID=cs.UserID

答案 1 :(得分:0)

这是查询

SELECT UserDCID AS UserDCCompForDelCount1 FROM CDICentral.dbo.UserDCComponent AS udc 
INNER JOIN (
      SELECT UserDCID FROM CDICentral.dbo.UserDC AS ud 
      EXCEPT 
      SELECT UserID FROM CVPLocal.dbo.CSWSecurity AS cs
     )Table T
ON T.UserDCID = udc.UserDCID 

答案 2 :(得分:0)

让我们从内部查询开始:

SELECT UserDCID FROM CDICentral.dbo.UserDC AS ud WHERE (
    UserID NOT IN(
        SELECT UserID FROM CVPLocal.dbo.CSWSecurity AS cs
    )
)

他们从表ud中选择表cs中没有匹配项的行,使用两者中都存在的字段UserID来连接表。

查询可以写成LEFT JOIN

SELECT ud.UserDCID
FROM CDICentral.dbo.UserDC AS ud
  LEFT JOIN CVPLocal.dbo.CSWSecurity AS cs
      ON ud.UserID = cs.UserID        # join the tables on common field `UserID`
WHERE cs.UserID IS NULL               # the row from `ud` has no match in `cs`

回到大查询(我剥离了上面重构的部分,因为它留在下面的解释中):

SELECT UserDCID AS UserDCCompForDelCount1
FROM CDICentral.dbo.UserDCComponent AS udc
WHERE(
    UserDCID IN (
        SELECT UserDCID ...
        )
    )
)

udc和结果集由字段udc连接时,此查询从UserDCID中选择内部查询(已剥离的)生成的结果集中匹配的行这两者都存在。

这是一个简单的INNER JOIN(让我们把重构的内部查询放回去):

SELECT udc.UserDCID AS UserDCCompForDelCount1
FROM CDICentral.dbo.UserDCComponent AS udc
  INNER JOIN CDICentral.dbo.UserDC AS ud
      ON udc.UserDCID = ud.UserDCID
  LEFT JOIN CVPLocal.dbo.CSWSecurity AS cs
      ON ud.UserID = cs.UserID
WHERE cs.UserID IS NULL

让我们看看新查询的作用:它选择与UserDCComponent s udc相关联的UserDC s(udCSWSecurity s cs ({{1}})记录。