-- ----------------------------
-- Records of topic
-- ----------------------------
INSERT INTO `topic` VALUES ('1', '唱歌');
INSERT INTO `topic` VALUES ('2', '跳舞');
INSERT INTO `topic` VALUES ('3', '电影');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
//用户表 user_id 用户id user_name 用户名
CREATE TABLE `user` (
`user_id` int(11) DEFAULT NULL,
`user_name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1001', '蔡徐坤');
INSERT INTO `user` VALUES ('1002', '蔡徐坤他奶奶');
INSERT INTO `user` VALUES ('1003', '蔡徐坤他爷爷');
INSERT INTO `user` VALUES ('1004', '蔡徐坤他爸爸');
select t1.topic_con,group_concat(t1.dynamic_con),sum(cc) from
(
(select y.dynamic_con,count(1) cc,t.topic_con from dy_info d
left join topic t on d.topic_id = t.topic_id
left join dynamic y on d.dynamic_id = y.dynamic_id
left join user u on y.user_id = u.user_id
where t.topic_id = '1'
group by y.dynamic_con,t.topic_con
order by cc desc
limit 0,3)
union all
(select y.dynamic_con,count(1) cc,t.topic_con from dy_info d
left join topic t on d.topic_id = t.topic_id
left join dynamic y on d.dynamic_id = y.dynamic_id
left join user u on y.user_id = u.user_id
where t.topic_id = '2'
group by y.dynamic_con,t.topic_con
order by cc desc
limit 0,3)
union all
(select y.dynamic_con,count(1) cc,t.topic_con from dy_info d
left join topic t on d.topic_id = t.topic_id
left join dynamic y on d.dynamic_id = y.dynamic_id
left join user u on y.user_id = u.user_id
where t.topic_id = '3'
group by y.dynamic_con,t.topic_con
order by cc desc
limit 0,3)
) t1
group by t1.topic_con
SELECT
a.*,c.cc
FROM
dy_info a
LEFT JOIN ( SELECT topic_id, count( 1 ) ccFROM dy_info GROUP BY topic_id ) c ON a.topic_id = c.topic_id
WHERE
( SELECT COUNT( 1 ) FROM dy_info b WHERE a.topic_id = b.topic_id AND a.dynamic_id > b.dynamic_id ) < 3
ORDER BY
a.topic_id;
分组合计放最后一列。。不知道符不符合你要求了。。