mysql根据另一个表更新和插入语句

时间:2014-04-18 22:35:45

标签: mysql sql database

我需要一些mysql语句的帮助,以便根据另一个表的内容在新表中插入和更新行。我将在自动pe​​rl代码中使用它,但mysql语句本身就是我遇到的麻烦。

我的第一个名为PROFILE的表看起来像这样:

+----------+---------------------------+
| ID       | NAME                      |
+----------+---------------------------+
| 0        | Default profile           |
| 04731470 | Development profile       |
| 87645420 | Core Base                 |
| a41401a0 | Core Test                 |
| ba0e3000 | Development profile child |
| e37fe780 | Test2                     |
+----------+---------------------------+

第二个名为DEPLOYMENT的列有这些列(还没有行):

+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| PROF_ID    | char(36)    | NO   | PRI | NULL    |       |
| NAME       | varchar(60) | NO   |     | NULL    |       |
| ID         | tinyint(4)  | NO   | MUL | NULL    |       |
+------------+-------------+------+-----+---------+-------+

ID.PROFILEPROF_ID.DEPLOYMENT的外键,我希望ID.PROFILE的所有值都放在PROF_ID.DEPLOYMENT中。然后,我希望根据NAME.DEPLOYMENT字段中的字词设置ID.DEPLOYMENTNAME.PROFILE字段。

以下显示了我想要做的事情,就插入语句而言,但由于“ERROR 1242(21000):Subquery返回的行超过1行而失败”:

INSERT INTO DEPLOYMENT(PROF_ID,NAME,ID) VALUES((select ID from PROFILE where NAME like '%core%'),'Core','2');
INSERT INTO DEPLOYMENT(PROF_ID,NAME,ID) VALUES((select ID from PROFILE where NAME like '%development%'),'Dev','3');
INSERT INTO DEPLOYMENT(PROF_ID,NAME,ID) VALUES((select ID from PROFILE where NAME not like '%development%' and not like '%core%'),'Default','1'); 

我不知道从哪里开始更新部分,但如果ID.DEPLOYMENT字段中的文字随任何字段发生变化,则NAME.DEPLOYMENTNAME.PROFILE字段应如上所示进行更改上面的话。

这是我要查找的DEVELOPMENT表格。

+----------+---------------+----+
| PROF_ID  | NAME          | ID |
+----------+---------------+----+
| 0        | Default       | 1  |
| 04731470 | Dev           | 3  |
| 87645420 | Core          | 2  |
| a41401a0 | Core          | 2  |
| ba0e3000 | Dev           | 3  |
| e37fe780 | Default       | 1  |
+----------+---------------+----+

然后,如果任何NAME.PROFILE信息发生变化,我希望更新语句。

很抱歉,如果这令人困惑,我不知道如何解释,我还在学习mysql。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

基本上摆脱values关键字:

INSERT INTO DEPLOYMENT(PROF_ID,NAME,ID)
    select ID, 'Core','2'
    from PROFILE
    where NAME like '%core%';

INSERT INTO DEPLOYMENT(PROF_ID,NAME,ID) 
    select ID, 'Dev', '3'
    from PROFILE
    where NAME like '%development%';

INSERT INTO DEPLOYMENT(PROF_ID,NAME,ID)
    select ID, 'Default', '1'
    from PROFILE
    where NAME not like '%development%' and not like '%core%'; 

顺便说一句,您可以使用条件表达式将这些组合成一个语句:

INSERT INTO DEPLOYMENT(PROF_ID,NAME,ID)
    select ID,
           (case when NAME like '%core%' then 'Core'
                 when NAME like '%development%' then 'Dev'
                 else 'Default'
            end)
           (case when NAME like '%core%' then '2'
                 when NAME like '%development%' then '3'
                 else '1'
            end)
    from PROFILE;