说我有以下内容:
CREATE TABLE newtable AS (
SELECT @rownum:=@rownum+1 as rownum, name, age FROM (
SELECT name, age FROM clubAmembers
UNION
SELECT name, age FROM clubBmembers
)
) AS atable
我怎样才能使它能够在SELECT联合之前“坚持在表格开头的新行”,以便从以下开始:
rownum | name| age
1 | "Jordan" | 6 <-- This is an arbitrarily inserted record with name="Jordan" age="6" that is not a part of any of the clubAmembers or clubBmembers table.
表格的其余部分(rownum 2及以后)将包含与clubAmembers联盟的实际结果,然后是clubBmembers。
基本上我正在寻找: 创建表 插入一行“Jordan”| 6 使用union执行select,使得第一行之后的行以“rownum = 2”开头,来自clubAmembers的所有数据等等。
如何做到最好?
答案 0 :(得分:1)
我不确定我是否做对了。但是你为什么不添加这样的另一个联盟:
CREATE TABLE newtable AS (
SELECT @rownum:=@rownum+1 as rownum, name, age FROM (
SELECT 1, "Jordan", 6
UNION ALL
SELECT name, age FROM clubAmembers
UNION ALL
SELECT name, age FROM clubBmembers
)
) AS atable
答案 1 :(得分:1)
“在表的开头”对关系数据库没有真正的意义,因为在使用ORDER BY
子句之前不能保证返回的订单结果,此时磁盘上的顺序无论如何都成为一个有争议的点
在您的情况下,由于您要保证结果子句中的订单(因此订购@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
请注意,这绝不保证clubAmembers
中的行比rownum
中的行低clubBmembers
。如果您想保证clubAmembers
的{{1}}较低rownum
,同时保留UNION
(与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
答案 2 :(得分:0)
您可以将create table statmenet与insert statmenet分开:
(INSERT INTO .... Values(...)
)INSERT INTO YourNewTable.... Values(YourSubQuery)
(Nr和tye列必须与您的子查询匹配)答案 3 :(得分:0)
我应该这样做,我相信:
CREATE TABLE newtable AS (
SELECT (@rownum:=IFNULL(@rownum,0)+1)+1 as rownum, name, age FROM (
SELECT name, age FROM clubAmembers
UNION
SELECT name, age FROM clubBmembers
) AS s
UNION ALL
SELECT 1, 'Jordan', 6
) AS atable
SQL小提琴演示:http://sqlfiddle.com/#!2/ab825/6