2009-08-26 86 views
1

我想插入选择,但我很困惑如何从选择只填入目标表中的1项,并用静态值填充其余部分。mysql插入选择难题

这是所有在存储过程中...所以...这里就是我试图做...

table:animals 
id |type| name 
1 |cat | mittens 
2 |cat | fluffy 
3 |dog | rex 

table people_with_pets 
persons_name | pets_name 
Arnold  | rex 

定义的变量所有者=“乔”;

so ... joe喜欢猫,我想将animals表中的所有名称与“joe”一起插入到people_with_pets表中。

所以,我想select name from animals where type like 'cats';

,并用“乔”到(在本例2)新的行中沿着people_with_pets插入所产生的值。

我不确定insert insert会不会让我这个,看起来好像可能,但我不知道如何使用它。

回答

1

INSERT INTO people_with_pets(persons_name,pets_name)SELECT'Joe',name FROM animals WHERE type ='cat';

4

INSERT INTO people_with_pets SELECT'Joe',name FROM animals WHERE type ='cat';

0

我假设你想要做的就是将所有的猫类型关联到Joe并插入到表people_with_pets中,通过使用单个插入选择语句来显示persons_name Joe和其他猫名称。

因此,有我所做的:

INSERT INTO people_with_pets 
(SELECT 'Joe', name FROM animals WHERE type like 'cat'); 

结果应该告诉你这一点:在设置

mysql> select * from people_with_pets; 

+--------------+-----------+ 
| persons_name | pets_name | 
+--------------+-----------+ 
| Arnold  | rex  | 
| Joe   | mittens | 
| Joe   | fluffy | 
+--------------+-----------+ 

3行(0.00秒)

+0

对不起,请注意,类型='猫“比”猫“更精确。就好像你有一只动物类型的鲶鱼一样,事情可能会变得混乱。虽然目前的情况都会返回相同的结果。 – user3068895