简体   繁体   English

SQL查询-选择前5行并仅在存在用户的情况下进一步选择行

[英]Sql query - selecting top 5 rows and further selecting rows only if User is present

I kind of stuck on how to implement this query - this is pretty similar to the query I posted earlier but I'm not able to crack it. 我有点固执于如何实现此查询-这与我之前发布的查询非常相似,但我无法破解它。

I have a shopping table where everytime a user buys anything, a record is inserted. 我有一个购物桌,每当用户购买任何东西时,都会插入一条记录。

Some of the fields are 一些领域是

* shopping_id (primary key)
* store_id
* user_id

Now what I need is to pull only the list of those stores where he's among the top 5 visitors: 现在,我只需要拉出他在前5名访客中的那些商店的列表即可:

When I break it down - this is what I want to accomplish: 当我分解它时,这就是我想要完成的工作:

* Find all stores where this UserA has visited
* For each of these stores - see who the top 5 visitors are.
* Select the store only if UserA is among the top 5 visitors.

The corresponding queries would be: 相应的查询将是:

select store_id from shopping where user_id = xxx
select user_id,count(*) as 'visits' from shopping 
where store_id in (select store_id from shopping where user_id = xxx)
group by user_id
order by visits desc
limit 5

Now I need to check in this resultset if UserA is present and select that store only if he's present. 现在,我需要在此结果集中检查UserA是否存在,并仅在他存在时选择该存储。 For example if he has visited a store 5 times - but if there are 5 or more people who have visited that store more than 5 times - then that store should not be selected. 例如,如果他去过一家商店5次-但是如果有5个或更多的人去过该商店5次以上,则不应选择该商店。

So I'm kind of lost here. 所以我有点迷路了。

Thanks for your help 谢谢你的帮助

This should do it. 这应该做。 It uses an intermediate VIEW to figure out how many times each user has shopped at each store. 它使用中间的VIEW来计算每个用户在每个商店购物的次数。 Also, it assumes you have a stores table somewhere with each store_id listed once. 另外,假设您在某处有一个store表,其中每个store_id都列出一次。 If that's not true, you can change SELECT store_id FROM stores to SELECT DISTINCT store_id FROM shopping for the same effect but slower results. 如果不是这样,您可以将SELECT store_id FROM stores更改为SELECT DISTINCT store_id FROM shopping以达到相同的效果,但效果较慢。

 CREATE VIEW shop_results (store_id, user_id, purchase_count) AS
     SELECT store_id, user_id, COUNT(*)
     FROM shopping GROUP BY store_id, user_id

 SELECT store_id FROM stores 
    WHERE 'UserA' IN 
      (SELECT user_id FROM shop_results 
       WHERE shop_results.store_id = stores.store_id 
       ORDER BY purchase_count DESC LIMIT 5)

You can combine these into a single query by placing the SELECT from the VIEW inside the sub-query, but I think it's easier to read this way and it may well be true that you want that aggregated information elsewhere in the system — more consistent to define it once in a view than repeat it in multiple queries. 您可以通过将SELECT的SELECT放在子查询中,将它们组合成一个查询,但是我认为这种方式更容易阅读,而且很可能确实希望在系统中的其他地方聚集这些信息。在视图中只定义一次,而不是在多个查询中重复一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM