MySQL:使用另一个表中的某些特定值在一个表中插入新记录

时间:2013-12-20 15:12:07

标签: mysql

我有两个包含以下字段的表:

  

TABLENAME:字符

Columns: AccountID, CharacterID, CharName, ID1, ID2, ID3, Level
     

TABLENAME:bankitem

Columns: CharID, Name, ItemID, Count, Type, ID1, ID2, ID3, Color, Effect1, Effect2, Effect3, LifeSpan, Attribute

我想在表bankitem中插入新行。我需要从一个表(字符)中查找信息,并将其中一些用作第二个表(bankitem)中的值。我只想定义CharID和ID1,ID2,ID3一次,尽管每行都有这些值。

例如,记录在字符表中:

1000, 1500, WarriorBob, 1200, 905, -2345, 180

查询/插入

SELECT * 
FROM  `character` 
WHERE  `CharName` LIKE  'WarriorBob'
LIMIT 0 , 1000

...

INSERT INTO bankitem (CharID, Name, ItemID, Count, Type, ID1, ID3, Color, Effect1, Effect2, Effect3, LifeSpan, Attribute)
values ('#CharacterID from WarriorBob's record in character table#', 'ZemstoneofSacrifice', '650', '1', '2', '#ID1 from WarriorBob's record in character table#', '#ID2 from WarriorBob's record in character table#', '#ID3 from WarriorBob's record in character table#', '0', '0', '0', '0', '3', '0')

2 个答案:

答案 0 :(得分:0)

您可以使用insert . . . select执行此操作:

INSERT INTO bankitem (CharID, Name, ItemID, Count, Type, ID1, ID3, Color, Effect1, Effect2, Effect3, LifeSpan, Attribute)
    select CharacterID, 'ZemstoneofSacrifice', '650', '1', '2', ID1, ID2, ID3, '0', '0', '0', '0', '3', '0'
    from character c
    where charname = 'WarriorBob';

答案 1 :(得分:0)

INSERT INTO bankitem 
(CharID, Name, ItemID, Count, Type, ID1, ID3, Color, Effect1, Effect2, Effect3, LifeSpan, Attribute)
(select CharacterID, ZemstoneofSacrifice', '650', '1', '2', ID1, ID2, ID3, '0', '0', '0', '0', '3', '0' 
from character where charname = 'WarriorBob')