如何联接两个具有相同属性的表?

时间:2018-12-12 05:34:12

标签: mysql sql database

我有两个表,我想使用两个表中的数据创建一个具有相同属性的新表。 以下是我正在尝试的代码

/* Create a table called NAMES */
CREATE TABLE NAMES(Id integer PRIMARY KEY, Name varchar(100));
CREATE TABLE GAMES(Id integer PRIMARY KEY, Name varchar(100));
CREATE TABLE JJ(Id integer PRIMARY KEY, Name varchar(100));

/* Create few records in this table */
INSERT INTO NAMES VALUES(1,'Tom');
INSERT INTO NAMES VALUES(2,'Lucy');
INSERT INTO NAMES VALUES(3,'Frank');
INSERT INTO NAMES VALUES(4,'Jane');
INSERT INTO NAMES VALUES(5,'Robert');
INSERT INTO GAMES VALUES(7,'Football');
INSERT INTO GAMES VALUES(6,'Rugby');
COMMIT;

/* Display all the records from the table */
SELECT * FROM NAMES;
SELECT * FROM GAMES;
INSERT INTO JJ (Id, Name) VALUES((SELECT * FROM NAMES), (SELECT * FROM GAMES));

SELECT * FROM JJ; 'Error: near line 21: sub-select returns 2 columns - expected 1'

3 个答案:

答案 0 :(得分:2)

这将适用于oracle

INSERT INTO JJ (Id, Name)((SELECT * FROM NAMES) union all(SELECT * FROM GAMES));

对于mysql:

   insert into JJ select * from Names union all select * from Games;

但是正如Zaynul所说,当两个主键匹配时,它将引发错误!

答案 1 :(得分:0)

您尝试合并两个表的方式并不更好,因为两个不同的表主键可能相同,这将在插入第三个表(重复键)时引发错误。我希望更改您的表结构,使所有三个表的主键自动递增并仅推送名称而不是ID

INSERT INTO JJ ( Name)
select name from (
SELECT name FROM NAMES
union all
SELECT name FROM GAMES
) t

答案 2 :(得分:0)

我建议将JJ声明为:

CREATE TABLE JJ (
    Id integer auto_increment PRIMARY KEY,
    Name varchar(100)
);

insert into jj (name)
    select name from names union all
    select game from games;