在一个INSERT..SELECT查询中双重插入

时间:2011-09-18 09:14:19

标签: mysql sql

例如,我有以下代码:

INSERT INTO table_prices(price, comment)
    SELECT a.price, 'first'
    FROM first_price AS a
UNION
    SELECT a.price, 'second'
    FROM second_price AS a;

我在表“table_prices”中得到了一个结果:

id                      price                   comment
1                       first_price1            first
2                       first_price2            first
3                       first_price3            first
...                     ...                     ...
15                      second_price1           second
16                      second_price2           second
...                     ...                     ...

但我需要以下内容:

id                      price                   comment
1                       first_price1            first
2                       second_price1           second
3                       first_price2            first
4                       second_price2           second
...                     ...                     ...

你能帮帮我 - 我怎么能实现这个目标? TIA!

2 个答案:

答案 0 :(得分:2)

您可以使用ORDER BY

ORDER BY id

答案 1 :(得分:1)

在union选择中排序行需要临时表,这样的东西应该起作用:

INSERT INTO table_prices(price, comment)
SELECT `price`,`comment`
FROM (
        SELECT a.price AS `price`, 'first' as `comment`
        FROM first_price AS a
        UNION
        SELECT a.price, 'second'
        FROM second_price AS a
    ) temp_table
ORDER BY `price`