如何从表中获得最多注释的用户

时间:2019-03-20 20:33:36

标签: mysql sql database

我正在尝试为用户提供评论最多的名字。我怎样才能做到这一点? 这是桌子。
下表是我要查询的数据库表的设置。

CREATE TABLE User(
        userid varchar(3),
        firstname varchar(20),
        lastname varchar(20),
        age int, 
        PRIMARY KEY(userid)
    )ENGINE=INNODB;


    CREATE TABLE Comment(
        commentid varchar(3),
        userid varchar(3),
        eventid varchar(3),
        title varchar(20),
        comment varchar(50),
        PRIMARY KEY(commentid),
        FOREIGN KEY(userid) REFERENCES AnonymousUser(userid),
        FOREIGN KEY(eventid) REFERENCES Event(eventid)
    )ENGINE=INNODB;


    INSERT INTO User VALUES('U01','Charles','Darwin',99);
    INSERT INTO User VALUES('U02','Keisha','Strawn',24);
    INSERT INTO User VALUES('U03','Denise','Malcolm',59);
    INSERT INTO User VALUES('U04','Dennis','Stewart',19);
    INSERT INTO User VALUES('U05','Robert','Johns',45);
    INSERT INTO User VALUES('U06','Marsha','Stewart',33);

    INSERT INTO Comment VALUES ('C01','A01','E01','Boring Event','This event was boring');
    INSERT INTO Comment VALUES ('C02','A02','E01','Nice Nice Event','This event was Nice');
    INSERT INTO Comment VALUES ('C03','A03','E03','Wow','This event was Amazing');
    INSERT INTO Comment VALUES ('C04','A01','E01','Very Sad','I missed this event');

我尝试的查询是

SELECT User.userid FROM User 
JOIN comment ON comment.userid = user.userid 
WHERE (SELECT COUNT(comment) 
FROM comment = (SELECT MAX(userid) FROM comment); 

2 个答案:

答案 0 :(得分:3)

SELECT 
    userid
FROM
    comment
GROUP BY userid
ORDER BY count(userid) DESC
LIMIT 1;

编辑:哦,您需要用户名。试试这个:

SELECT firstname 
FROM user 
WHERE userid = (
    SELECT 
        userid
    FROM
        comment
    GROUP BY userid
    ORDER BY count(userid) DESC
    LIMIT 1
);

答案 1 :(得分:0)

查询获得最多评论的名字是

select a.firstname, max(a.comment_count) from (
    select u.firstname, count(c.commentid) comment_count
    from user u join comment c on u.userid = c.userid
    group by u.firstname
)a;

话说,我注意到

  1. 对表'comment'的约束之一指向表'AnonymousUser'外键(用户ID)引用AnonymousUser(用户ID)。您尚未共享该表的create table语句。 我必须从表定义中删除此约束,以便在数据库中成功创建该表
CREATE TABLE Comment(
  commentid varchar(3),
  userid varchar(3),
  eventid varchar(3),
  title varchar(20),
  comment varchar(50),
  PRIMARY KEY(commentid)
);   
  1. 表'comment'的数据集没有与'user.userid'值匹配的用户ID

我更新了'comment'表插入,因此执行查询时可以获得一些结果。

INSERT INTO Comment VALUES ('C01','U01','E01','Boring Event','This event was boring');
INSERT INTO Comment VALUES ('C02','U01','E01','Nice Nice Event','This event was Nice');
INSERT INTO Comment VALUES ('C03','U03','E03','Wow','This event was Amazing');
INSERT INTO Comment VALUES ('C04','U06','E01','Very Sad','I missed this event');