我想从加入2存在表创建一个新表。 这些表的关系是id表1是来自id表2的FK。
我已经尝试了这个并且它不起作用:
CREATE TABLE joined2tables
(SELECT detil_bet.*, detail_game.*
FROM detil_bet
INNER JOIN detail_game
ON detil_bet.id_game = detail_game.id_game);
答案 0 :(得分:3)
您可以使用
SELECT something, somethingElse
INTO YourNewTable
FROM someTable
JOIN someOtherTable ON someCondition
这将从结果中继承数据类型。
答案 1 :(得分:2)
您需要先创建表,然后插入行。查看现有表以查找正确的列,然后执行SELECT INTO
例如,如果您有以下两个表:
CREATE TABLE Employee (
EmployeeId int,
Salary money,
DateOfLastHokeyPokey datetime,
PRIMARY KEY( EmployeeId )
);
CREATE TABLE Manager (
EmployeeId int,
ManagingDepartmentId int,
DateCompletedManagementTraining datetime,
PRIMARY KEY( EmployeeId )
);
您可以创建下表:
CREATE TABLE SalaryManagerReport (
EmployeeId int,
ManagingDepartmentId int,
Salary money,
PRIMARY KEY( EmployeeId )
);
要填充此表,您可以执行以下操作:
INSERT INTO SalaryManagerReport
SELECT e.EmployeeId, m.ManagingDepartmentId, e.Salary
FROM Employee e
INNER JOIN Manager m ON e.EmployeeId=m.EmployeeId;
答案 2 :(得分:1)
试试这个:
SELECT
* FROM
detil_bet, detail_game WHERE
detil_bet.id_game = detail_game.id_game
答案 3 :(得分:0)
我猜你已经有了答案。但是为了更清晰,我会发布这个答案,它是scsimon和Robert Columbia答案的组合。
方法1:
SELECT e.EmployeeId, m.ManagingDepartmentId, e.Salary
INTO SalaryManagerReport
FROM Employee e
INNER JOIN Manager m ON e.EmployeeId=m.EmployeeId;
上面的查询在你运行一次时运行正常,但是如果你多次尝试执行它,就会发出一个错误,说已经有了一个具有该名称的对象。因此,您必须删除该表并再次运行它。
方法2:
INSERT INTO SalaryManagerReport
SELECT e.EmployeeId, m.ManagingDepartmentId, e.Salary
FROM Employee e
INNER JOIN Manager m ON e.EmployeeId=m.EmployeeId;
这在所有情况下都可以正常工作,因为表创建查询与插入查询不同。
因此,如果您想多次执行它,请转到第二个答案,或者第一个答案。