2009-08-17 91 views
8

隨機值在Microsoft SQL Server 2008中,我有一個產品表:更新SQL表與其他表

ID |名稱| DefaultImageId

而且一個與圖片:

ID | ProductId |字節

我想運行一個Update語句,該語句使用ProductId列中與產品相關的Images表中的隨機Id更新Products表中所有記錄上的DefaultImageId。

任何人都可以幫忙嗎?應該是任何SQL冠軍(這顯然不是我)簡單...

回答

5

您可以通過NEWID進行訂購,以獲取每行更新的隨機數。

UPDATE 
    Products 
SET 
    DefaultImageId = 
    (
     SELECT TOP 1 
      Id 
     FROM 
      Images 
     WHERE 
      Images.ProductId = Products.Id 
     ORDER BY 
      NEWID() 
    ) 
+11

此解決方案似乎將隨機選擇的值分配給每個正在更新的行。有沒有一種方法來分配每一行更新與從源表中隨機選擇一個不同的值(在你的例子中的圖像)? – philreed 2015-07-02 13:43:43

+0

請看看剛剛發佈的解決方案是否解決了這個問題,@philreed – jacoblambert 2015-09-22 11:58:50

1

檢查了這一點。

Update Products 
Set DefaultImageId = (
SELECT top 1 Id 
From Images 
Where 1=1 
and Products.Id = Images.ProductId 
ORDER BY NEWID() 
) 
+0

消息147,級別15,狀態1,行2 聚合不應出現在WHERE子句中,除非它是在含有HAVING子句或選擇列表在子查詢中,並且列被聚集的是外部參考。 – MartinHN 2009-08-17 18:43:45

+0

我很抱歉,我糾正了它。 – 2009-08-17 18:47:11

3

另一種可能的解決方案

UPDATE 
    Products 
SET 
    DefaultImageId = 
    (
     SELECT TOP 1 
      Id 
     FROM 
      Images 
     ORDER BY 
      NEWID(), Products.Id 
    ) 
+0

太好了,如果圖片表長度小於產品,這將不會保存空值。 – DevC 2015-08-11 17:31:24

0

試試這個(上的AdventureWorks):

它更新的人表的所有行從產品表中一個新的隨機名稱。

begin tran 
--show initial state: 
select top 25 * from person.person order by BusinessEntityID 

update person.person 
set 
FirstName = otherTable.Name 
from 
(select BusinessEntityID, row_number() over (order by newid()) as row_num from person.person) p2 
,(select ProductId, Name, row_number() over (order by newid()) as row_num from production.product) as otherTable 
where 
person.person.BusinessEntityID=p2.BusinessEntityID 
and (p2.row_num%500)=(otherTable.row_num%500) -- deal with tables with different rowcount 

--check results: 
select top 25 * from person.person order by BusinessEntityID 

rollback tran 

或者試用SQL小提琴類似的查詢: http://sqlfiddle.com/#!3/8b719/1

7

尋址@ philreed的問題與選擇的答案:

有沒有用不同的更新來分配各行的方式從源表中隨機選擇的值 ?

UPDATE Products 
SET DefaultImageId = t2.Id 
FROM Products t1 
CROSS APPLY (
    SELECT TOP 1 Id 
    FROM Images 
    WHERE t1.Id = t1.Id 
    ORDER BY newid() 
    ) t2  
+0

這解決了我在每行上獲取相同隨機數的問題。需要「where t1.Id = t1.Id」才能使它工作,我最初沒有注意到它,儘管交叉應用是被接受的答案和這個之間的唯一區別。 – 2017-12-09 16:18:42

+0

對於記錄(沒有雙關語意圖),這是不是非常高性能,如果對一個大ish數據集使用(我正在更新一個電話號碼從10000個隨機電話號碼列表爭奪一個300k成員的表,並且我目前在33分鐘,想知道多長時間...) – jleach 2018-02-15 16:06:46

+0

也許你可以發佈細節? – jacoblambert 2018-02-15 16:26:09