如何编写MySQL查询

时间:2017-05-27 07:01:49

标签: mysql sql database

我有两张桌子:

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更新为下一个值,该值将从所有代码 code_id中获取。
现在我有client_id,即来自survey表的65,并希望将stage_id更新为 163 (即基于排序的所有代码表中的下一个code_id在srno

我试过的是

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;

此查询将所有代码stage_id更新为 73 ,我希望将其更新为 163 (具体取决于{{ 1}})

2 个答案:

答案 0 :(得分:2)

我会在更新中使用联接来获取基于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而没有任何间隙。第一次加入的目的是获取当前stage_id的srno。然后第二个连接获得下一个srno的stage_id。

答案 1 :(得分:0)

您在子查询中order by之前错过了limit

因此,如果不接触您的其余查询,我只是尝试添加order by,它似乎可以根据您的需要从stage id 72首先更新163。< / p>

Rextester Demo

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"
ORDER BY SRNO
limit 1) 
where client_id=65;