1

我有以下表格,

清单:

ID varchar2(33)
Name varchar2(100)

用户:

ID varchar2(33)
Name varchar2(100)

用户列表

ID auto-generated
UserId references ID from Users
ListingId references ID from Listing

我想找到最喜欢的用户列表(在这种情况下是 User_listing 表中计数最高的列表。例如,如果 user_listing 表包含<id,user_id,listing_id>,

1 1 2
1 1 3
1 2 3
1 3 3

最喜欢的列表是 3

这是运行正确的查询吗?

Select Listing.name
  from Listing
 where Listing.id = (Select p.id 
                       from User_listing p, User_listing q
                     having count(p.id) > count(q.id)
                      GROUP BY p.id)

另外,如果我必须打印出前 5 个最爱,我该怎么做?

4

2 回答 2

0

这取决于您使用的是哪种 SQL,至少对于您获得前 5 条记录的部分。在 SQL Server 中,您将使用“Select Top 5”。在 MySQL、Postgres、Oracle 等中,它是“限制 5”。

这是一个 MySQL 解决方案,它选择了有关前 5 个列表的所有信息:

SELECT * FROM listing
JOIN 
(SELECT listing_id
FROM user_listing
GROUP BY listing_id 
ORDER BY count(listing_id) DESC
LIMIT 5) as top_five ON top_five.listing_id=listing.id;

如果您只需要顶级列表的 id,则可以这样做:

SELECT listing_id
    FROM user_listing
    GROUP BY listing_id 
    ORDER BY count(listing_id) DESC
    LIMIT 5
于 2012-09-29T05:27:12.407 回答
0

甲骨文方式

select * from (
    select ListingID, Name, count(*) FrequencyOfListingID
      from UserListing, Listing
     where Listing.ID = UserListing.ListingID
     group by ListingID 
     order by 2 desc) 
 where rownum < 6 

MsSql 方式未测试

    select Top 5 ListingID, Name, count(*) FrequencyOfListingID
      from UserListing, Listing
     where Listing.ID = UserListing.ListingID
     group by ListingID 
     order by 2 desc) 

MySQl 方式未经测试

    select ListingID, Name, count(*) FrequencyOfListingID
      from UserListing, Listing
     where Listing.ID = UserListing.ListingID
     group by ListingID 
     order by 2 desc 
     Limit 5
于 2012-09-29T05:38:54.587 回答