简体   繁体   中英

MySQL - selecting first 3rd, second 3rd, and third 3rd from multiple tables

Given table1, table2, and table3 (assume they are identical in structure), is it possible to select the first 1/3 records of table1, table2, and table3? Then the second 1/3? Then the last 1/3?

The first 1/3 record :

SELECT *
FROM
(
    SELECT *
    FROM
    (
       SELECT * FROM Table1 
       UNION ALL 
       SELECT * FROM Table2
       UNION ALL
       SELECT * FROM Table3 
       UNION ALL
    ) sub
    ORDER BY ID DESC
    LIMIT 3
) t 
ORDER BY Id ASC
LIMIT 1

The second 2/3::

SELECT *
FROM
(
    SELECT *
    FROM
    (
       SELECT * FROM Table1 
       UNION ALL 
       SELECT * FROM Table2
       UNION ALL
       SELECT * FROM Table3 
       UNION ALL
    ) sub
    ORDER BY ID DESC
    LIMIT 3
) t 
ORDER BY Id ASC
LIMIT 2, 1

The last 1/3 record:

SELECT *
FROM
(
    SELECT *
    FROM
    (
       SELECT * FROM Table1 
       UNION ALL 
       SELECT * FROM Table2
       UNION ALL
       SELECT * FROM Table3 
       UNION ALL
    ) sub
    ORDER BY ID DESC
    LIMIT 3
) t 
ORDER BY Id DESC
LIMIT 1

Try to play with a LIMIT and a OFFSET clause like :

SELECT column FROM table1 LIMIT X OFFSET Y
union
SELECT column FROM table2 LIMIT X OFFSET Y+10
union
SELECT column FROM table3 LIMIT X OFFSET Y+20

but you must parameterize the LIMIT and the OFFSET.. that's a way

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