我有两张桌子:
mysql> select * from survey;
+-----------+-----------+----------+--------+-----------+
| survey_id | client_id | stage_id | by_ref | no_branch |
+-----------+-----------+----------+--------+-----------+
| 2 | 65 | 72 | P | 15 |
| 3 | 67 | 72 | D | 2 |
+-----------+-----------+----------+--------+-----------+
2 rows in set (0.07 sec)
mysql> select * from allcode where code_type="MARKETING_STAGES";
+------------------+---------+------+--------------------+
| code_type | code_id | srno | code_name |
+------------------+---------+------+--------------------+
| MARKETING_STAGES | 72 | 1 | Enquiry |
| MARKETING_STAGES | 73 | 3 | Meeting |
| MARKETING_STAGES | 74 | 4 | Presentation |
| MARKETING_STAGES | 75 | 5 | Review / Follow up |
| MARKETING_STAGES | 76 | 6 | Negotiation |
| MARKETING_STAGES | 77 | 7 | Order |
| MARKETING_STAGES | 78 | 8 | Agreement |
| MARKETING_STAGES | 162 | 9 | Complete |
| MARKETING_STAGES | 163 | 2 | Tender |
+------------------+---------+------+--------------------+
9 rows in set (0.04 sec)
我想将调查表的
stage_id
更新为下一个值,该值将从allcodecode_id
中获取。现在我有一个
client_id
表,即65 fromsurvey
表,并希望将stage_id
更新为163(即,基于srno
排序的allcode表的下一个代码id)我试过的是
update survey as s
set s.stage_id=
(select code_id from allcode
where code_id > (select stage_id from (select * from survey where client_id=65 )as su)
and code_type="MARKETING_STAGES"
limit 1)
where client_id=65;
此查询将allcode的
stage_id
更新为73,我希望将其更新为163(取决于srno
) 最佳答案
我将使用更新中的联接来获取下一个基于code_id
的srno
:
update survey s
inner join allcode a1 on s.stage_id=a1.code_id
inner join allcode a2 on a1.srno=a2.srno-1
set s.stage_id=a2.code_id
where a1.code_type='MARKETING_STAGES' and a2.code_type='MARKETING_STAGES' and s.client_id=65
我假设
srno
字段增量为1,没有任何间隙。第一个联接的目的是获取当前阶段的srno。然后第二个连接获取下一个srno的stage\u id。