我有一个简单的select语句,例如:
SELECT *
FROM [customer] AS [c]
INNER JOIN [customertype] AS [ct] ON [c].[CustTypeKey] = [ct].[CustTypeKey]
INNER JOIN [ProjectCustomer] AS [pc] ON [c].[CustomerKey] = [pc].[CustomerKey]
INNER JOIN [Project] AS [p] ON [pc].[ProjectKey] = [p].[ProjectKey]
INNER JOIN [Address] AS [A] ON [P].ProjectGuid = [A]. [AddressGuid]
WHERE [ct].[CustTypeKey] = 7
AND [c].[Name] = 'Customer'
AND [A].[RegionKey] = 2
OR [A].[RegionKey] = 3
由于某些原因,WHERE
子句无法正常工作。我按[A].[RegionKey] = 2
和[A].[RegionKey] = 3
进行过滤。因此,我想获取所有具有RegionKey
2和3的项,但它只获取具有RegionKey
3的值,并且我确定我也具有RegionKey
2的项。
此WHERE
子句在做什么?
答案 0 :(得分:1)
更改此:
AND [A].[RegionKey] = 2
OR [A].[RegionKey] = 3
对此:
AND ([A].[RegionKey] = 2
OR [A].[RegionKey] = 3)
或者这个:
AND [A].[RegionKey] IN (2,3)
然后确保WHERE
子句中的其他条件正确,因为其中至少有一个可能过度过滤。
答案 1 :(得分:0)
SELECT
*
FROM [customer] AS [c]
INNER JOIN [customertype] AS [ct] ON [c].[CustTypeKey] = [ct].[CustTypeKey]
INNER JOIN [ProjectCustomer] AS [pc] ON [c].[CustomerKey] = [pc].[CustomerKey]
INNER JOIN [Project] AS [p] ON [pc].[ProjectKey] = [p].[ProjectKey]
INNER JOIN [Address] AS [A] ON [P].ProjectGuid = [A]. [AddressGuid]
WHERE [ct].[CustTypeKey] = 7
AND [c].[Name] = 'Customer'
AND ([A].[RegionKey] = 2 OR [A].[RegionKey] = 3)
您需要在受OR子句影响的两个项目周围添加()。现在,OR子句使之前的AND语句无效。
您先前的查询是用简单的英语说的: “返回所有具有保管类型键7,客户名称和区域键2的结果,或仅返回具有区域键3的结果(因此,如果区域键为3,则不必成为客户或客户类型为7)。
您的代码现在应该可以正确运行。