我运行正确的SQL查询吗?

时间:2012-09-29 05:02:52

标签: sql

我有以下表格,

清单:

ID varchar2(33)
Name varchar2(100)

用户:

ID varchar2(33)
Name varchar2(100)

User_Listing

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)

另外,如果我必须打印出前五名的最爱,我该怎么办呢?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

Oracle方式

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