我需要一些mysql语句的帮助,以便根据另一个表的内容在新表中插入和更新行。我将在自动perl代码中使用它,但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.PROFILE
是PROF_ID.DEPLOYMENT
的外键,我希望ID.PROFILE
的所有值都放在PROF_ID.DEPLOYMENT
中。然后,我希望根据NAME.DEPLOYMENT
字段中的字词设置ID.DEPLOYMENT
和NAME.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.DEPLOYMENT
和NAME.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。任何帮助表示赞赏。
答案 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;