【问题标题】:2 Tables - Query them with one another and store pk's from each table into a new table2 个表 - 相互查询并将每个表中的 pk 存储到一个新表中
【发布时间】:2012-04-03 07:31:39
【问题描述】:

假设我有 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 是否相等,如果相等,将每个的主键存储在新的关系表中?

【问题讨论】:

    标签: mysql sql create-table


    【解决方案1】:

    可移植的 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 ...

    【讨论】:

    • 因为我在 MySQL 中执行此操作,所以我可以执行以下操作:CREATE TABLE 随便(first_id int NOT NULL,second_id int NOT NULL,common_random_attribute varchar(255))AS SELECT...(你在上面放的?)
    • @BackpackOnHead:没有CREATE TABLE Whatever AS SELECT... 。 AFAIK 使用 SELECT 时无法指定列/类型等
    • 我按照我写的方式(在这个回复中)尝试了它,它奏效了!非常感谢!
    【解决方案2】:

    可能是这样的:

    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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      相关资源
      最近更新 更多