Do I need a while loop to insert based on conditions?

落爺英雄遲暮 提交于 2020-02-06 07:17:24

问题


I want to insert values in a column based on the following conditions. Name of the column to be inserted is project_renewal.

If decimal exists in project_code, insert the numbers after decimals.

SELECT substring_index(project_code, '.', -1)
FROM projects where
project_code like '%.%'

If no decimal, insert 0.

SELECT project_code
FROM projects where
project_code not like '%.%'

Order of insert must be the same as the order of reading values from project_code.


回答1:


 INSERT IGNORE INTO outtable (code)
 SELECT IF (project_code LIKE '%.%'
     , substring_index(project_code, '.', -1)
     , 0)
 FROM projects



回答2:


You can do it like this:

INSERT INTO tablename(project_renewal)
SELECT trim(trailing '0' from substring_index(project_code, '.', -1)) + 0
FROM projects

See the demo.

If you want to update a column in the same table then do it with an UPDATE statement:

UPDATE projects
SET project_renewal = trim(trailing '0' from substring_index(project_code, '.', -1)) + 0

See the demo.



来源:https://stackoverflow.com/questions/60083029/do-i-need-a-while-loop-to-insert-based-on-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!