Sql server 2005 sql server 2005查询-唯一随机父行的随机子行
我得到了一个父表“ProductCategory”和一个子表“Product”。我的查询返回3个随机产品:Sql server 2005 sql server 2005查询-唯一随机父行的随机子行,sql-server-2005,random,parent-child,Sql Server 2005,Random,Parent Child,我得到了一个父表“ProductCategory”和一个子表“Product”。我的查询返回3个随机产品: SELECT TOP (3) ProductId FROM Product ORDER BY NEWID(); 我想增强该查询,以实现所有产品都来自不同的产品类别。因此,获取唯一类别的查询将是: SELECT TOP (3) ProductCategoryId FROM ProductCategory ORDER BY NEWID(); 我不知道如何结合
SELECT TOP (3) ProductId
FROM Product
ORDER BY NEWID();
我想增强该查询,以实现所有产品都来自不同的产品类别。因此,获取唯一类别的查询将是:
SELECT TOP (3) ProductCategoryId
FROM ProductCategory
ORDER BY NEWID();
我不知道如何结合这两个查询来实现我的目标。显而易见的疑问
SELECT TOP (3) p.ProductId
FROM Product p
where p.productcategory_ProductCategoryId in
(
SELECT TOP (3) ProductCategoryId pc
FROM ProductCategory pc
ORDER BY NEWID()
)
ORDER BY NEWID();
不起作用。似乎忽略了内部select语句。我还尝试使用EXISTS语句或连接表。结果都一样
有人有主意吗?提前多谢 像这样的怎么样?我能够使用临时表和游标完成这项任务。这是一个较长的步骤,但它可以工作
create table #temp(
productID int
,CategoryID int
)
declare @CategoryID int
declare ID_Cursor cursor
for select ProductCategoryID from ProductCategory order by NEWID()
open ID_Cursor
FETCH NEXT FROM ID_Cursor INTO @CategoryID
WHILE @@FETCH_STATUS = 0 and (select COUNT(*) from #temp)<3
BEGIN
if (@CategoryID not in (select CategoryID from #temp))
Begin
insert into #temp
SELECT top(1) ProductID, @CategoryID
FROM [Product]
order by NEWID()
END
FETCH NEXT FROM ID_Cursor INTO @CategoryID
END
CLOSE ID_Cursor
DEALLOCATE ID_Cursor
select * from #temp
drop table #temp
您必须解耦这两个查询,这是一个解决方案 根据ProductCategoryId,关联子查询以获得随机产品。ProductCategoryId的唯一性由外部查询处理
SELECT TOP 3
(SELECT TOP 1
ProductId
FROM
Product P
WHERE
P.ProductCategoryId = PC.ProductCategoryId
ORDER BY
NEWID()
) AS ProductId
FROM
ProductCategory PC
WHERE
EXISTS (SELECT *
FROM
Product Pex
WHERE
Pex.ProductCategoryId = PC.ProductCategoryId)
ORDER BY
NEWID();
我现在明白了
在Burbidge87中,我添加了一个where条件:
FROM Product p
where @CategoryID = p.ProductCategory_ProductCategoryId
就这样。再次感谢
JJ