「在表的開始處」對於關係數據庫並不真正有意義,因爲直到使用ORDER BY
子句時纔會保證返回訂單結果,此時磁盤上的訂單無論如何都會成爲一個爭論點。
在你的情況,因爲你想在你的結果子句來保證訂單(因此訂貨@rownum
,你將不得不使用ORDER BY
喜歡的東西:
CREATE TABLE newtable AS (
SELECT @rownum:[email protected]+1 as rownum, name, age
FROM (
SELECT 'Jordan' AS name, 6 AS age, 0 AS ord
UNION
SELECT name, age, 1 AS ord FROM clubAmembers
UNION
SELECT name, age, 1 AS ord FROM clubBmembers
ORDER BY ord
)
) AS atable
注意,在任何時候,做這樣的保證那麼clubAmembers
中的行將比clubBmembers
中的行具有更低的rownum
。如果你想保證clubAmembers
具有較低rownum
,同時保持UNION
(相對於UNION ALL
)語義,您可以使用以下命令:
CREATE TABLE newtable AS (
SELECT @rownum:[email protected]+1 as rownum, name, age
FROM (
SELECT 'Jordan' AS name, 6 AS age, 0 AS ord
UNION ALL
SELECT name, age, 1 AS ord FROM clubAmembers
UNION ALL
SELECT name, age, 2 AS ord FROM clubBmembers AS b
WHERE NOT EXISTS(SELECT 1 FROM clubAmembers AS a
WHERE a.name = b.name AND a.age = b.age)
ORDER BY ord
)
) AS atable
注意如果{name
,age
}可以在clubXmembers
表內被複制,你將需要添加DISTINCT
:
...
SELECT DISTINCT name, age, 1 AS ord FROM clubAmembers
UNION ALL
...
按照註釋中的要求,如果你有一個clubCmembers
表,你會怎麼做:
CREATE TABLE newtable AS (
SELECT @rownum:[email protected]+1 as rownum, name, age
FROM (
SELECT 'Jordan' AS name, 6 AS age, 0 AS ord
UNION ALL
SELECT name, age, 1 AS ord FROM clubAmembers
UNION ALL
SELECT name, age, 2 AS ord FROM clubBmembers AS b
WHERE NOT EXISTS(SELECT 1 FROM clubAmembers AS a
WHERE a.name = b.name AND a.age = b.age)
SELECT name, age, 3 AS ord FROM clubCmembers AS c
WHERE NOT EXISTS(SELECT 1 FROM clubAmembers AS a
WHERE a.name = c.name AND a.age = c.age)
AND NOT EXISTS(SELECT 1 FROM clubBmembers AS b
WHERE b.name = c.name AND b.age = c.age)
ORDER BY ord
)
) AS atable
訂單隻能使用一個ORDER BY子句中可靠地建立。這是因爲大多數SQL(包括UNION)都是「基於集合」的。 – 2013-02-06 05:37:42
SELECT @rownum:= @ rownum + 1建立命令,如果我只是聯合clubAmembers和clubBmembers(如編號1到... n的成員)。如果在保留rownum命令的同時保留這些表的聯合之前,我不可能插入一行,那麼完成我想要的操作的最佳選擇是什麼? – Setsuna
它不會建立由* inside * union產生的元素的順序:選擇操作稍後發生。它可能按預期工作。或者它可能不會。 – 2013-02-06 05:40:34