On Microsoft SQL Server 2008, I have a table with Products:
Id | Name | DefaultImageId
And one with Images:
Id | ProductId | Bytes
I want to run an Update statement, that updates the DefaultImageId on all records in the Products table with a random Id from the Images table that is related to the Product via the ProductId column.
Can anyone help out? Should be simple for any SQL Champ (Which is obviously not me)..
Check this out.
You can do an order by on a NEWID to get a random number for every row of your update.
This has been down marked and comments added indicating it does not solve the problem. I think the confusion has come from where people have not realised the original question requests a random image be selected for each product, hence the where clause with Product Id. Have provided a full script with data set below. It adds five products and three images for each product. Then randomly sets the default image id for each product.
Try this one (on AdventureWorks):
It updates all rows of the person table with a new random name from the product table.
Or try a similar query on SQL Fiddle: http://sqlfiddle.com/#!3/8b719/1
Another possible solution
Addressing @philreed's issue with the selected answer: