MySQL:如何从每个用户获得五个帖子?

时间:2016-04-05 13:53:03

标签: php mysql join left-join

我想从一个表中选择用户,并通过为每个表设置id来检查另一个表中的LIMIT 5

这是我拥有的,但我不能重复使用,第二个联盟中的a.id

SELECT a.id AS USER,
       p.id AS post_id
FROM (
        (SELECT a.id
         FROM `user` a
         WHERE a.date=...)
      UNION
        (SELECT p.id
         FROM `post` p
         WHERE p.user_id=a.id LIMIT 5)`` `) AS post

谢谢你,aloha

1 个答案:

答案 0 :(得分:1)

查询可能如下所示:

主要查询:

SELECT 
t.userID,
t.postID
FROM 
(
         SELECT
          user.id AS userID,
          post.id AS postID,
          IF (@prev = post.user_id ,@cn := @cn + 1 ,@cn := 0) SL,
          @prev := post.user_id
        FROM (SELECT @cn := 0, @prev := 0) var,post
        INNER JOIN user ON user.id = post.user_id
        ORDER BY post.user_id) t
WHERE t.SL < 5;

该查询将为每个用户选择5个帖子。

<强> TEST:

无法添加SQL FIDDLE。

所以这里有一些带有架构的测试数据来检查查询。

DROP TABLE IF EXISTS `post`;
CREATE TABLE `post` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `post` VALUES ('1', '71');
INSERT INTO `post` VALUES ('2', '66');
INSERT INTO `post` VALUES ('3', '66');
INSERT INTO `post` VALUES ('4', '71');
INSERT INTO `post` VALUES ('5', '66');
INSERT INTO `post` VALUES ('6', '71');
INSERT INTO `post` VALUES ('7', '71');
INSERT INTO `post` VALUES ('8', '71');
INSERT INTO `post` VALUES ('9', '66');
INSERT INTO `post` VALUES ('10', '66');
INSERT INTO `post` VALUES ('11', '66');
INSERT INTO `post` VALUES ('12', '66');
INSERT INTO `post` VALUES ('13', '71');
INSERT INTO `post` VALUES ('14', '91');

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
);
INSERT INTO `user` VALUES ('66');
INSERT INTO `user` VALUES ('71');
INSERT INTO `user` VALUES ('91');


SELECT 
*
FROM post;

<强>结果:

id  user_id
1   71
2   66
3   66
4   71
5   66
6   71
7   71
8   71
9   66
10  66
11  66
12  66
13  71
14  91

SELECT * FROM user;

<强>结果:

id
66
71
91

每个用户查询的帖子总数:

SELECT 
user_id,
COUNT(*) totalPost
FROM post 
GROUP BY user_id;

<强>结果:

user_id  totalPost
66         7
71         6
91         1

最终结果:

userID postID
66       2
66       3
66       5
66       12
66       11
71       1
71       13
71       8
71       7
71       6
91       14