2016-07-15 141 views
0

我有一个简单的表用户(名称,城市,国家),需要添加几个值,其中一些值相同(城市,国家)。有没有更好的方式来插入旁边的数据:SQL插入查询用于乘以具有共享值的行

insert into Users (name, city, country) values 
("John", "Paris", "France"), 
("Anna", "Paris", "France"), 
("Peter", "Paris", "France"), 
("Mary", "Paris", "France") 

谢谢

+0

您正在使用哪种RDBMS? –

+0

一般不会,但如果您没有将其用作手动查询,则应该使用“准备好的语句”。无论你的项目语言是什么,它都有它们。您只需设置一次城市和国家的参数并循环(设置和插入)即可。这对你的网站/应用程序会更好,另外Prepared Statements可以保证你的SQL注入安全。 – coladict

回答

2

您可以使用类似下面的查询:

insert into Users (name, city, country) 
select name, city, country 
from (select 'John' as name union all 
     select 'Anna' union all 
     select 'Peter' union all 
     select 'Mary') as t1 
cross join (select 'Paris' as city, 'France' as country) as t2 
0

您应该能够使用变量。因此,它看起来像......

set @city="Paris"; 

set @country="France"; 

insert into Users(name, city, country) values 
("John", @city, @country) 
0

虽然可以简化这个有点通过在特定的RDBMS语法使用变量,你被卡住插入相同的值到表的多个行由于设计决策您在定义Users表时所做的。

问题是您的表格不是正常化,这意味着相同的信息多次出现。解决这个问题的正确方法是定义一个国家表格,一个引用它的城市表格,并将Users表格更改为参考Cities

0
Your solution is correct normaly but try to replace " by ' else try it: 

insert into Users (name, city, country) 
select * 
from (
select 'John', 'Paris', 'France' union all 
select 'Anna', 'Paris', 'France' union all 
select 'Peter', 'Paris', 'France' union all 
select 'Mary', 'Paris', 'France' 
) tmp