一半的Mysql结果

时间:2016-05-25 11:44:04

标签: mysql

我希望将我的结果拆分为一半并立即添加这样的行

主表

item  qty  rate
===============
test1  10   22
test2  11   25
test3  12   22
test4  14   50
test5  16   26
test6  55   20
test7  60   60

我想要这样

item  qty  rate   item1  qty1  rate1
====================================
test1  10   22    test2   16    26
test3  11   25    test4   16    26
test5  12   22    test6   16    26
test7  14   50    test8   16    26

 item  qty  rate   item1  qty1  rate1
    ====================================
    test1  10   22   test5  12   22
    test2  16   26   test6  16   26
    test3  11   25   test7  14   50 
    test4  16   26   test8  16   26

1 个答案:

答案 0 :(得分:1)

这需要时间,具体取决于表格的大小。解决方案是......

SELECT ROUND(COUNT(*)/2) INTO @cnt FROM tobehalf;

SELECT t1.item, t1.qty, t1.rate, t2.item as item1, t2.qty as qty1, t2.rate as rate1 FROM
(
SELECT * FROM (SELECT tobehalf.*, @rownum1 := @rownum1 + 1 AS rank
FROM tobehalf, (SELECT @rownum1 := 0) r1) d1
WHERE d1.rank <= @cnt
) t1
LEFT JOIN
(
SELECT * FROM (SELECT tobehalf.*, @rownum2 := @rownum2 + 1 AS rank
FROM tobehalf, (SELECT @rownum2 := 0) r2) d2
WHERE d2.rank > @cnt
) t2 on t1.rank = t2.rank - @cnt