简体   繁体   中英

How to create a new column and add values to it based on a condition in MySQL?

alter table marks
add divisible_by_tenvarchar(50) default 'null'
SELECT marks, divisible_by_ten, IF(marks %10 =0 , "yes", "no");

this code

I have tried the above code and surely there is a mistake. there are two columns studentID and marks. and I need to arrange them in student ID order and also create a new column and say "yes" or "no" if marks are divisible by 10.

Just do this first:

alter table marks add divisible_by_ten char(3);

Then, update data in it:

alter table marks add divisible_by_ten char(3);
update marks
set divisible_by_ten = case when marks % 10 = 0 then 'yes' else 'no' end;

Example

create table marks (marks int);
insert into marks values (10), (11);
alter table marks add divisible_by_ten char(3);
update marks
set divisible_by_ten = case when marks % 10 = 0 then 'yes' else 'no' end;
select * from marks;

Result

marks | divisible_by_ten ----: |:--------------- 10 |  yes 11 | no

See: https://dbfiddle.uk/?rdbms=mysql_5.6&fiddle=85e32cde86e13e05bf2c1fdaa3fbdf7e

Alternate

You don't really have to create a field to store that divisible information. If marks change, you will have to update divisible column manually or programmatically or put a trigger on the table.

Instead, don't add divisible column. Just create a view.

create view marks_10 as 
select
  marks, 
  case when marks % 10 = 0 then 'yes' else 'no' end as divisible_by_10
from marks;

Then, you can call the view at any point to get fresh data along with divisible_by_10 dynamic column like this:

select * from marks_10;

Example of that: https://dbfiddle.uk/?rdbms=mysql_5.6&fiddle=4370997be4c64fd89908f8f35fe95fda

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM