嵌套插入选择

时间:2011-12-03 17:44:12

标签: mysql sql insert

我有递归表:

CREATE TABLE IF NOT EXISTS `Table1` (
   `Id_table1` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
   `Name` VARCHAR(45) NOT NULL ,
   `Parent_Id` INT UNSIGNED NOT NULL ,
   PRIMARY KEY (`Id_table1`) ,
   INDEX `fk_Table1_Table1` (`Parent_Id` ASC) ,
   UNIQUE INDEX `Id_UNIQUE` (`Id_table1` ASC) ,
   CONSTRAINT `fk_Table1_Table1`
      FOREIGN KEY (`Parent_Id` ) REFERENCES `Table1` (`Id_table1` )
      ON DELETE NO ACTION
      ON UPDATE NO ACTION)
   ENGINE = InnoDB;

我尝试执行:

INSERT INTO table1 (`Name`, `Parent_Id`)
   VALUES ('name123', SELECT Id_table1
                      from table1
                      where table1.`Name` = 'sampleName')

不幸的是,收到错误。

数据表:

id: 1 name: name1   parent_id: null
id: 2 name: name11  parent_id: null
id: 3 name: name123 parent_id: null

知道如何执行此插入吗?

1 个答案:

答案 0 :(得分:5)

尝试以下INSERT

INSERT INTO table1 (Name, Parent_Id)
SELECT 'name123', t.Id_table1
FROM table1 AS t
WHERE t.Name = 'sampleName';