简体   繁体   中英

Pagination in one to many relationship with PHP and MySQL

I Want to display 6 records from a database table. There is one-to many relationships between 2 tables. With custom mapper, I mapped these records as follows.

$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"
                         ]
                    ]
      ]
]

QUERY

"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; 

This query will return data like

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

But I need another 4 more records of another 4 persons. I'm using php and mysql5.7.

If I understand your needs :

    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';

At last, I found the answer to this question.

"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"; 

this will return exact 6 persons messages and we can easily manage pagination. If you have another simple option. please post here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM