有人告诉我我应该返回10行数据,但是我的输出不正确。 我正在尝试获取每个用户发表的评论和帖子的数量。我希望这些列成为昵称,评论(包含已发表的评论总数)和帖子(包含已发表的总数帖子)。我只想显示发表了1个或更多评论或帖子的用户。
当前尝试:
SELECT postauthors.nickname,
(select COUNT(postcomments.nickname) AS commentsMade
FROM postcomments
where
postcomments.nickname = postauthors.nickname) as Comments,
(select COUNT(posts.postID) AS posts
FROM posts where posts.postID = postauthors.postID) as Posts
FROM postauthors
GROUP BY nickname
HAVING Comments >=1 OR Posts >=1;
只有得到回报。
EBebe 2 1
joey 0 1
ricko 0 1
smithz 0 1
表 postauthors
CREATE TABLE postauthors ( nickname varchar(255) NOT NULL,
postID int(11) NOT NULL,
PRIMARY KEY (nickname,postID),
KEY postIDPA (postID),
CONSTRAINT nicknamePA FOREIGN KEY (nickname) REFERENCES users (nickname),
CONSTRAINT postIDPA FOREIGN KEY (postID) REFERENCES posts (postID) )
ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `postauthors` VALUES ('EBebe',1),('joey',2),('ricko',3),('ricko',4),('smithz',5),('EBebe',6),('ricko',7);
表后评
CREATE TABLE `postcomments (nickname varchar(255) NOT NULL,
postID int(11) NOT NULL,
datetime datetime NOT NULL,
content varchar(1000) NOT NULL,
PRIMARY KEY (nickname,postID,datetime),
KEY postIDPC (postID),
CONSTRAINT nicknamePC FOREIGN KEY (nickname) REFERENCES users (nickname),
CONSTRAINT postIDPC FOREIGN KEY (postID)
参考帖子(postID)
INSERT INTO postcomments VALUES ('barbs',2,'2018-09-10 07:50:12','Working :('),('EBebe',2,'2018-09-10 10:02:20','Day off - so I\'ll probably sleep all day!'),('EBebe',5,'2018-09-11 16:06:02','Weightlifting!'),('GC',5,'2018-09-11 18:45:39','I like to walk with my dog'),('j75',2,'2018-09-10 07:51:00','Studying :('),('jerry',3,'2018-09-10 14:50:10','Food is the best!!!!!'),('kdog',6,'2018-09-12 09:10:14','The Bunnies!'),('niknik',6,'2018-09-12 08:30:30','Storm or Roosters');
表帖子
CREATE TABLE posts (postID int(11) NOT NULL,
datetime datetime NOT NULL,
content varchar(1000) NOT NULL,
PRIMARY KEY (postID);
INSERT INTO posts VALUES (1,'2018-09-10 00:01:30','Hi, nice to meet everyone!'),(2,'2018-09-10 07:45:00','What is everyone doing today?'),(3,'2018-09-10 13:20:49','How amazing is food!!! Had the best lunch!'),(4,'2018-09-11 09:03:11','Feeling better today than yesterday'),(5,'2018-09-11 14:12:23','How do you like to get exercise?'),(6,'2018-09-11 23:45:30','Who do you think will win the NRL grand final?'),(7,'2018-09-12 07:02:12','Today was a great day :)');
我希望返回10行文本,因为在10个名称中,列中带有数字的名称可以一个为NULL,但不能同时为两个
答案 0 :(得分:0)
Post和Postauthors之间的关系方向错误。 Table Post应该添加一个外键,例如昵称。
一位作者应该可以发表多次。
您的where子句未引用正确的表。
然后该语句应如下所示:
SELECT postauthors.nickname,
(select COUNT(*) FROM postcomments where nickname = postauthors.nickname) as Comments,
(select COUNT(*) FROM posts where nickname = postauthors.nickname) as Posts
FROM postauthors GROUP BY nickname
HAVING
(select COUNT(*) FROM postcomments where nickname = postauthors.nickname) >=1 OR
(select COUNT(*) FROM posts where nickname = postauthors.nickname) >=1;