简体   繁体   中英

MySQL query with limit on parent table not on child table

I have two tables students and student_updates .

  CREATE TABLE IF NOT EXISTS `students` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `name` varchar(20) NOT NULL,
          `class` varchar(20) NOT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB

Data: 
    id  name class
    1   A    X
    2   B    IX
    3   C    X
    4   D    XI

Every Student has zero or many updates.

    CREATE TABLE IF NOT EXISTS `student_updates` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `sid` int(11) NOT NULL,
                          `updates` text NOT NULL,
                          PRIMARY KEY (`id`),
                          KEY `fk_sid` (`sid`)
                ) ENGINE=InnoDB 
            ALTER TABLE `student_updates`
              ADD CONSTRAINT `fk_sid` FOREIGN KEY (`sid`) REFERENCES `students` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

Data : 
        id  sid updates
        1   1   U1
        2   1   U2
        3   1   U3
        4   1   U4
        5   2   U5
        6   2   U6
        7   2   U7

Now I want a query to fetch records of student with their update but with limit on student (parent table) rather than limit on child table (student_updates). For example:

SELECT s.id, s.name, su.id, su.updates
FROM students AS s
LEFT JOIN `student_updates` AS su ON s.id = su.sid
LIMIT 2  

Result:

id  name    id  updates
1   A   1   U1
1   A   2   U2

But I want 2 parent record with their all updates (child records).

For example:

id  name    id  updates
1   A   1   U1
1   A   2   U2
1   A   3   U3
1   A   4   U4
2   B   5   U5
2   B   6   U6
2   B   7   U7

But limiting the result based on student table (parent table)

Most specially I need an optimize solution because students table has around 1 million record and student_updates has more than 40 million records.

Create a subquery with a limit, then create the join from there.

SELECT s.id, s.name, su.id, su.updates
FROM (select id, name from students limit 2) AS s
LEFT JOIN `student_updates` AS su ON s.id = su.sid
SELECT s.id, s.name, su.id, su.updates
FROM students AS s
LEFT JOIN `student_updates` AS su ON s.id = su.sid
where s.id in (select id from students limit 2)

You could use CROSS JOIN

SELECT s.id, s.name, su.id, su.updates
FROM students AS s
CROSS JOIN (select su.id, su.updates FROM `student_updates` limit 1 AS su WHERE s.id = su.sid)

use IN operator for where clause

SELECT s.id, s.name, su.id, su.updates
FROM students AS s
LEFT JOIN `student_updates` AS su ON s.id = su.sid
WHERE su.sid IN ('1','2');

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