SQL SELECT在另一个表中按引用顺序排序

时间:2015-02-17 07:33:16

标签: sql

我有一个包含表'Users','Pickles'和'Likes'的SQL数据库。

表'喜欢'的结构如下:id,userID,pickleID

当用户喜欢泡菜时,会在“喜欢”中添加一行。

在这样的情况下,我想从数据库中拉出前10个最喜欢的泡菜。有没有简单的方法呢?

5 个答案:

答案 0 :(得分:4)

听起来您正在寻找likes表中聚合查询的联接:

在ANSI SQL中:

SELECT   p.*
FROM     pickles p
JOIN     (SELECT   pickleID, COUNT(*) AS cnt
          FROM     likes
          GROUP BY pickleID) l ON p.pickleID = l.pickleID
ORDER BY cnt DESC
FETCH    FIRST 10 ROWS ONLY

请注意,某些RDBMS的专有语法大致相当于fetch子句,并且可能不支持ANSI语法,尤其是在早期版本中。

MySQL的:

SELECT   p.*
FROM     pickles p
JOIN     (SELECT   pickleID, COUNT(*) AS cnt
          FROM     likes
          GROUP BY pickleID) l ON p.pickleID = l.pickleID
ORDER BY cnt DESC
LIMIT    10

Microsoft SQL Server:

SELECT   TOP 10 p.*
FROM     pickles p
JOIN     (SELECT   pickleID, COUNT(*) AS cnt
          FROM     likes
          GROUP BY pickleID) l ON p.pickleID = l.pickleID
ORDER BY cnt DESC

12c之前的Oracle:

SELECT * 
FROM   (SELECT   p.*
        FROM     pickles p
        JOIN     (SELECT   pickleID, COUNT(*) AS cnt
                  FROM     likes
                  GROUP BY pickleID) l ON p.pickleID = l.pickleID
        ORDER BY cnt DESC) 
WHERE  rownum <= 10

编辑:
要回答评论中的问题,如果至少有10个泡菜没有投票,则上述查询将仅返回投票的泡菜。为了在没有投票的情况下添加其他泡菜,您可以将join替换为left join。这将允许没有投票的泡菜显示,好像他们有null个投票数。然后,您可以使用coalesce将这些null视为0,然后应用相同的顺序。这是ANSI-SQL查询的一个示例。其他可以以类似的方式修改:

SELECT    p.*, COALESCE (cnt, 0) AS votes
FROM      pickles p
LEFT JOIN (SELECT   pickleID, COUNT(*) AS cnt
           FROM     likes
           GROUP BY pickleID) l ON p.pickleID = l.pickleID
ORDER BY  votes DESC
FETCH     FIRST 10 ROWS ONLY

答案 1 :(得分:1)

在SQL-SERVER

select * from Pickles
where id in 
( 
    select top 10 pickleID 
    from Likes 
    group by pickleID
    order by COUNT(*) desc
)

答案 2 :(得分:1)

试试这个:

SELECT TOP 10 
pickleID,
COUNT(pickleID) AS NumberOfLikes
FROM Likes 
GROUP BY pickleID
ORDER BY 1 DESC

答案 3 :(得分:0)

如果您使用的是MS SQL

通过sql查询按顺序尝试分组并选择前10条记录。

Select top 10 PicklelId, Count(*) total from Likes group by PicklelID order by total desc

答案 4 :(得分:0)

这是如何获得最受欢迎的泡菜(前10名):

select top 10
   P.PickleID,
   P.PickleName,
   count(L.id) as TotalLikes
from
   Pickles P
   left outer join Likes L on L.PickleID = P.PickleID
group by
   P.PickleID,
   P.PickleName
order by
   sum(L.id) desc