“在表的开头”对关系数据库没有真正意义,因为在您使用ORDER BY
子句之前不能保证返回的顺序结果,此时磁盘上的顺序无论如何都成为一个有争议的问题。
在您的情况下,由于您想保证结果子句中的顺序(因此 ordering @rownum
,您将不得不使用ORDER BY
。例如:
CREATE TABLE newtable AS (
SELECT @rownum:=@rownum+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
请注意,这绝不保证行 inclubAmembers
将低于rownum
行 in clubBmembers
。如果要保证clubAmembers
具有 lower rownum
,同时保持UNION
(versus UNION ALL
) 的语义,可以使用以下内容:
CREATE TABLE newtable AS (
SELECT @rownum:=@rownum+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:=@rownum+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