MySQL - 从多个表中选择第一个,第二个第三个和第三个第三个

时间:2012-11-01 12:54:04

标签: mysql sql

鉴于table1,table2和table3(假设它们在结构上相同),是否可以选择table1,table2和table3的前1/3记录?然后第二个1/3?然后是最后的1/3?

2 个答案:

答案 0 :(得分:0)

前1/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 1

第二个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

最后1/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 DESC
LIMIT 1

答案 1 :(得分:0)

尝试使用LIMIT和OFFSET子句,如:

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

但你必须参数化LIMIT和OFFSET ..这是一种方式