与php和mysql的一对多关系分页

35g0bw71  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(350)

我想显示数据库表中的6条记录。两个表之间存在一对多关系。使用CustomMapper,我将这些记录Map如下。

$result  = [
   0=>[
        "name"=>"jithin",
        "phone"=>"907856",
        "messages"=>[
                      0=>[
                          "title"=>"text messgae"
                         ],
                      1=>[
                          "title"=>"Data messgae"
                         ]
                    ]
      ],
    1=>[
        "name"=>"Rijin",
        "phone"=>"90247856",
        "messages"=>[
                      0=>[
                          "title"=>"text messgae"
                         ],
                      1=>[
                          "title"=>"Data messgae"
                         ]
                    ]
      ]
]

查询

"SELECT u.* , m.* FROM user u INNER JOIN messages m ON m.userId = u.id
 WHERE m.date BETWEEN "12-12-2015" AND "12-12-2018" LIMIT 0, 6;

此查询将返回如下数据

userId | name | messages|
-------|------|---------|
1      |jithin| hai     |
1      |jithin| hello   |
1      |jithin| Why?    |
2      |Rijin | hai     |
2      |Rijin | Where   |
2      |Rijin | Why?    |
-------------------------

但我还需要另外4个人的记录。我正在使用php和mysql5.7。

k2fxgqgv

k2fxgqgv1#

如果我了解你的需求:

SELECT u.id, u.userName , m.message
    FROM user u 
    INNER JOIN messages m ON m.userId = u.id
    INNER JOIN (SELECT u.id as user_id FROM user u LIMIT 0, 6) as users
        ON users.user_id = u.id
    WHERE m.date BETWEEN '12-12-2015' AND '12-12-2018';
wz1wpwve

wz1wpwve2#

最后,我找到了这个问题的答案。

"SELECT u.* , m.* FROM user u 
 INNER JOIN messages m ON m.userId = u.id
 INNER JOIN (SELECT DISTINCT u.id as user_id FROM user u 
             INNER JOIN messages m ON m.userId = u.id
             WHERE m.date BETWEEN "12-12-2015" 
             AND "12-12-2018" LIMIT 0, 6) 
 AS distinct_users ON distinct_users.user_id=u.id
 WHERE m.date BETWEEN "12-12-2015" AND "12-12-2018";

这将返回准确的6人消息,我们可以很容易地管理分页。如果你有另一个简单的选择。请在这里张贴。

相关问题