我希望得到最喜欢的照片。我怎样才能做到这一点?

时间:2018-02-22 20:17:53

标签: sql oracle greatest-n-per-group

我试过这个

select max(c) from (select pid as p, count(likeuid) as c from likes group by pid);

但是这只给了我最喜欢的图片数量。 我想要最喜欢的图片的pid。

这是我的mini instadb数据库 tables description

喜欢桌子

CREATE TABLE  "LIKES" 
   (    "PID" NUMBER(6,0) NOT NULL ENABLE, 
    "LIKEUID" NUMBER(6,0) NOT NULL ENABLE, 
    "COMMENTS" VARCHAR2(140) NOT NULL ENABLE, 
     CONSTRAINT "LIKES_UK1" UNIQUE ("PID", "LIKEUID", "COMMENTS") ENABLE
   ) ;ALTER TABLE  "LIKES" ADD CONSTRAINT "LIKES_FK2" FOREIGN KEY ("PID")
      REFERENCES  "PICTURES" ("PID") ON DELETE CASCADE ENABLE;ALTER TABLE  "LIKES" ADD CONSTRAINT "LIKES_FK3" FOREIGN KEY ("LIKEUID")
      REFERENCES  "USERS" ("USERID") ON DELETE CASCADE ENABLE;

3 个答案:

答案 0 :(得分:0)

如果你只想要一个喜欢最喜欢的人,我认为这个SQL就是你想要的:

SELECT
    p, 
    RANK() OVER (ORDER BY c DESC) toplikes
FROM
    (
    SELECT
        pid AS p, 
        count(likeuid) AS c 
    FROM 
        likes 
    GROUP BY 
        pid
    ORDER BY 
        count(likeuid) DESC
    )
WHERE 
    toplikes = 1

答案 1 :(得分:0)

我认为这就是你想要的:

public static List<Person> test1() {
    ...; 
    return persons;
} 

答案 2 :(得分:0)

以下查询对我有用

select pid from likes group by pid having count(pid)=(select max(count(pid)) from likes group by pid);