3

我有两个名为 Product 和 ProductImage 的表。

两个表之间存在 1-n 关系。一种产品和多个图像,具体取决于产品。

我想创建一个产品视图,并且我想从 ProductImage 表中为每个产品随机获取一个图像。

示例数据:http ://sqlfiddle.com/#!6/43c69

我想要像下面这样的东西。

+-----------+------+-------------+
| ProductId | Name |   WebPath   |
+-----------+------+-------------+
|         1 | Foo  | foowebpath2 |
|         2 | Boo  | boowebpath3 |
|         3 | Zoo  | zoowebpath1 |
+-----------+------+-------------+

或者

+-----------+------+-------------+
| ProductId | Name |   WebPath   |
+-----------+------+-------------+
|         1 | Foo  | foowebpath1 |
|         2 | Boo  | boowebpath1 |
|         3 | Zoo  | zoowebpath6 |
+-----------+------+-------------+

或者

+-----------+------+-------------+
| ProductId | Name |   WebPath   |
+-----------+------+-------------+
|         1 | Foo  | foowebpath4 |
|         2 | Boo  | boowebpath2 |
|         3 | Zoo  | zoowebpath5 |
+-----------+------+-------------+

或者等等……

每次都必须不一样。

4

2 回答 2

3

你应该试试这个

SELECT *, (SELECT TOP 1 WebPath FROM ProductImage PI 
WHERE PI.ProductId = P.ProductId order by NEWID()  ) as WebPart from Product P

检查这个小提琴http://sqlfiddle.com/#!6/43c69/16

于 2013-06-08T11:14:42.143 回答
1
WITH Image AS
(
  SELECT *, RAND(ProductImageId) R
  FROM ProductImage 
)

SELECT p.*, i2.* FROM Product P
INNER JOIN 
    (SELECT ProductId, MIN(R) R
     FROM Image
     GROUP BY ProductId) i1 ON i1.ProductId = p.ProductId
INNER JOIN Image i2 ON i2.R = i1.R
于 2013-06-08T11:32:11.693 回答