如何重写以下查询,以使子查询成为联接的一部分?还是其他更好的方法?
Declare @CR varchar(32)
SELECT count(*)
FROM [dbo].[TableC]
INNER JOIN [dbo].[TableCS] ON [TableCS].[CSI] = [TableC].[CSI]
INNER JOIN [dbo].[TableI] ON [TableI].TableIId = [TableC].[TableIId]
WHERE [TableC].[CR] = @CR
AND [TableI].[POR] = (SELECT POR FROM TableI inner join [TableC] on TableI.TableIId = [TableC].TableIId and [TableC].CR = @CR)
AND [TableCS].[Consider] = 1
答案 0 :(得分:0)
您应该能够使用别名将子查询转换为您的主查询...
SELECT
COUNT(*)
FROM
[dbo].[TableC]
INNER JOIN
[dbo].[TableCS]
ON [TableCS].[CSI] = [TableC].[CSI]
INNER JOIN
[dbo].[TableI]
ON [TableI].TableIId = [TableC].[TableIId]
(
TableI AliasedTableI
INNER JOIN
TableC AliasedTableC
ON AliasedTableI.TableIId = AliasedTableC.TableIId
AND AliasedTableC.CR = @CR
)
ON AliasedTableI.POR = TableI.POR
WHERE
[TableC].[CR] = @CR
AND [TableCS].[ConsiderInExistenceChecks] = 1
这不可能是最好的也是最后的重构。但是,不知道您的模式或业务规则是我唯一可以为您编写的安全模式。
答案 1 :(得分:0)
如果POR是TableC的列,那么...
Declare @CR varchar(32)
SELECT count(*)
FROM [dbo].[TableC]
INNER JOIN [dbo].[TableCS] ON [TableCS].[CSI] = [TableC].[CSI]
INNER JOIN [dbo].[TableI] ON [TableI].TableIId = [TableC].[TableIId] and [TableC].CR = @CR AND [TableI].[POR]= [TableC].POR
WHERE [TableC].[CR] = @CR
AND [TableCS].[Consider] = 1