雙插

2011-09-18 47 views
2

例如,我有以下代碼:雙插

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!

+0

爲什麼會發生這種事秩序? – meze

+0

你爲什麼需要這個/你確定你需要嗎?這是因爲你需要一個特殊的ID連接到特定的數據(這很奇怪,因爲它只是一個'隨機'ID),或者它只是爲了輸出目的(然後我不打擾你如何獲取它表,但它更多的是輸出的東西) – Nanne

回答

2

您可以使用ORDER BY

ORDER BY id 
+0

thx很棒!這個對我有用! – dizpers

1

行排序工會選擇需要臨時表中,這樣的事情應該工作:

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` 
+0

這是另一個好方法,thx!:) – dizpers