为一系列活跃的广告商店随机选择每家商店的前 3 名列表
我正在尝试显示一个商店列表,每个商店都有 3 个随机商品,如果它们有 3 个或更多列表,则它们正在积极做广告。我有 3 张表:一张用于商店 - “Shops”,一张用于列表 - “Listings”,一张用于跟踪活跃广告商 - “AdShops”。
使用下面的语句,返回的列表是随机的,但是我没有得到每个商店返回的正好 3 个列表(行)。
SELECT AdShops.ID, Shops.url, Shops.image_url, Shops.user_name AS shop_name,
Shops.title, L.listing_id AS listing_id, L.title AS listing_title,
L.price as price, L.image_url AS listing_image_url, L.url AS listing_url
FROM AdShops INNER JOIN
Shops ON AdShops.user_id = Shops.user_id INNER JOIN
Listings AS L ON Shops.user_id = L.user_id
WHERE (Shops.is_vacation = 0 AND Shops.listing_count > 2 AND
L.listing_id IN
(SELECT TOP 3 L2.listing_id
FROM Listings AS L2
WHERE L2.listing_id IN
(SELECT TOP 100 PERCENT L3.listing_id
FROM Listings AS L3
WHERE (L3.user_id = L.user_id)
)
ORDER BY NEWID()
)
)
ORDER BY Shops.shop_name
我很困惑。有人对如何修复它有任何想法吗?
理想的解决方案是每个商店一条记录,其中 3 个列表(和相关数据)位于列而不是行中 – 这可能吗?
I’m trying to display a list of shops each with 3 random items from their shop, if they have 3 or more listings, that are actively advertising. I have 3 tables: one for the shops – “Shops”, one for the listings – “Listings” and one that tracks active advertisers – “AdShops”.
Using the below statement, the listings returned are random however I’m not getting exactly 3 listings (rows) returned per shop.
SELECT AdShops.ID, Shops.url, Shops.image_url, Shops.user_name AS shop_name,
Shops.title, L.listing_id AS listing_id, L.title AS listing_title,
L.price as price, L.image_url AS listing_image_url, L.url AS listing_url
FROM AdShops INNER JOIN
Shops ON AdShops.user_id = Shops.user_id INNER JOIN
Listings AS L ON Shops.user_id = L.user_id
WHERE (Shops.is_vacation = 0 AND Shops.listing_count > 2 AND
L.listing_id IN
(SELECT TOP 3 L2.listing_id
FROM Listings AS L2
WHERE L2.listing_id IN
(SELECT TOP 100 PERCENT L3.listing_id
FROM Listings AS L3
WHERE (L3.user_id = L.user_id)
)
ORDER BY NEWID()
)
)
ORDER BY Shops.shop_name
I’m stumped. Anyone have any ideas on how to fix it?
The ideal solution would be one record per store with the 3 listings (and associated data) were in columns and not rows – is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我没记错的话,下面的查询应该给你每个 user_id 至少有 3 个随机的 Listing_id。
If I'm not mistaken, below query should give you every user_id having at least 3 random listing_id's.
感谢 Lieven 提供了解决问题的关键。完整解决方案如下:
享受吧!
Thanks to Lieven for the key to the problem. Full solution is as follows:
Enjoy!