在Insert查询中使用select查询获取相同的表名

时间:2009-10-14 07:16:36

标签: mysql

是否可以在“插入”查询中使用“选择”查询,但条件是我想为“选择”和“插入”查询使用相同的表名。
例如<登记/> mysql> insert into sample_elements (name,position,ownerel) values ('Namespace1', select id from sample_elements where name='Namespace1',0);

请指导我。

5 个答案:

答案 0 :(得分:16)

将插入更改为如下所示:

insert into sample_elements (name,position,ownerel) select 'Namespace1',id,0 from sample_elements where name='Namespace1';

基本上不使用值而只使用select语句并将带编码的值作为列插入

答案 1 :(得分:2)

我认为你可以做到。您可以使用:

INSERT INTO table (..fields) SELECT ..fields.. FROM table;

答案 2 :(得分:0)

我不知道mysql但您可以尝试以下方法吗?

insert into sample_elements select name, id, 0 from sample_elements where name='Namespace1'

答案 3 :(得分:0)

我不确定。我认为这个插入内部的选择已经存在或用于什么目的。

由于

答案 4 :(得分:-1)

这是另一种使用'SET'结构的格式。我更喜欢这种格式的大部分SQL,因为字段名称与值配对 - 使维护比完全依赖于定位的字段/值列表更容易。

INSERT INTO sample_elements SET
name = 'Namespace1',
position = (SELECT id FROM sample_elements WHERE name='Namespace1'),
ownere1 = 0;
相关问题