问题
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