MySQL将2个查询联接到同一张表

时间:2018-10-31 04:53:19

标签: mysql join

嗨,我正在尝试将以下查询合并到一张表中

第一个查询是

SET @row_number = 0;

SELECT 
    (@row_number:=@row_number + 1) AS Batch, t_stamp as Date, Total
FROM
    food
ORDER BY t_stamp ASC
LIMIT 45

第二个查询是

SET @row_number = 45;
SELECT 
    (@row_number:=@row_number + 1) AS Batch, t_stamp as Date, Total
FROM
    food
ORDER BY t_stamp ASC
LIMIT 50, 45

我要实现的是下面的表格

Batch |  Date  |  Total  |     Batch  |  Date     |  Total
 1      9.00am      10          46      12.30pm       10 
 2      10.00am     10          47      1.00pm        10
 -                            -
 45     12.00pm     10          90      2.00pm        10

任何建议都会很棒。 谢谢

2 个答案:

答案 0 :(得分:0)

尝试加入两个子查询:

SET @rn1 = 0;
SET @rn2 = 0;

SELECT
    t1.Batch, t1.Date, t1.Total, t2.Batch, t2.Date, t2.Total
FROM
(
    SELECT 
        (@rn1:=@rn1 + 1) AS Batch, t_stamp AS Date, Total
    FROM food
    ORDER BY t_stamp
    LIMIT 45
) t1
INNER JOIN
(
    SELECT 
        (@rn2:=@rn2 + 1) AS Batch, t_stamp AS Date, Total
    FROM food
    ORDER BY t_stamp
    LIMIT 50, 45
) t2
    ON t1.Batch = t2.Batch
ORDER BY
    t1.Date;

答案 1 :(得分:0)

您可以尝试使用UNION ALL合并两个数据集

SET @row_number = 0;
SET @row_number1 = 45;

select * from
(SELECT 
    (@row_number:=@row_number + 1) AS Batch, t_stamp as Date, Total
FROM
    food
ORDER BY t_stamp ASC
LIMIT 45
)A
union all

select * from
(
SELECT 
    (@row_number1:=@row_number1 + 1) AS Batch, t_stamp as Date, Total
FROM
    food
ORDER BY t_stamp ASC
LIMIT 50, 45
)
B