为什么我不能在子查询中应用条件?

时间:2010-01-14 23:57:27

标签: sql sql-server subquery

我想做的是:

select Store.Id, (select COUNT(*) from StoreProduct
where StoreProduct.Store_id = Store.Id) as _count from Store where _count > 3

SQL Server说它无效,因为列名'_count'无效。如果我宣布它为什么它无效?

6 个答案:

答案 0 :(得分:4)

select Id as StoreId, count(*) as ProductCount
from StoreProduct
group by Id
having count(*) > 3

另一种方式

select S.Id, count(SP.ProductId) as ProductCount
from Store S
left join StoreProduct SP on (SP.Store_id = S.Id)
group by S.Id
having COUNT(SP.ProductId) > 3

假设,StoreProduct表中的唯一列名为ProductId

答案 1 :(得分:3)

由于SQL中的评估顺序,它对WHERE子句无效。 WHERE子句在列表中排名第二,因此只能看到FROM子句中存在的项(首先计算)。 This old article有评估顺序的细分。我确定那里有一个更新的。

答案 2 :(得分:1)

'as'用于在逻辑上重命名查询中的字段。您不能使用它来重命名表,这是您的子查询返回的表,即使我们通过上下文知道子查询返回的表只包含一行。

我希望这会有所帮助。

答案 3 :(得分:0)

尝试使用以字母而不是下划线开头的名称。

答案 4 :(得分:0)

你为什么不尝试这个?

select Store_id as Id, COUNT(1) as acount
from StoreProduct
group by Store_id
having count(1) > 3

答案 5 :(得分:0)

为什么不试试这个:

select a.StoreId,count(*) as TotProducts
from Store a
join StoreProduct b on b.storeId=a.storeID
group by a.storeID
having count(*) > 3

这似乎是你想要完成的事情?