2表 - 相互查询并将每个表中的pk存储到一个新表中

时间:2012-04-03 07:31:40

标签: mysql sql create-table

所以我想说我有TABLE1和TABLE2。

CREATE TABLE TABLE1
(
first_id int NOT NULL,
first_random_attribute varchar(255)
primary key(first_id)
)

CREATE TABLE TABLE2
(
second_id int NOT NULL,
second_random_attribute varchar(255)
primary key(second_id)
)

如何将TABLE1和TABLE2相互比较,创建一个关系表,检查它们的x_random_attribute是否相等,如果是,则将每个主键的主键存储在新的关系表中?

2 个答案:

答案 0 :(得分:2)

便携式SQL

CREATE TABLE Whatever (
  first_id int NOT NULL,
  second_id int NOT NULL,
  common_random_attribute varchar(255)
  );

INSERT Whatever (first_id, second_id, common_random_attribute)
SELECT
    t1.first_id, t2.second_id, t1.first_random_attribute
FROM
    TABLE1 t1
    JOIN
    TABLE2 t2 ON t1.first_random_attribute = t2.second_random_attribute;

具体替代方案:

  • MySQL允许您在一个声明中CREATE TABLE AS SELECT ...
  • SQL Server / Sybase有SELECT .. INTO ...

答案 1 :(得分:0)

也许是这样的:

CREATE TABLE RealatedTable(
   first_id int NOT NULL,
   second_id int NOT NULL
);

INSERT INTO RealatedTable(first_id,second_id)
SELECT 
   TABLE1.first_id,
   TABLE2.second_id 
FROM 
   TABLE1
JOIN TABLE2 
   ON TABLE1.first_random_attribute=second_random_attribute