Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if value is not empty, then insert mysql

Tags:

mysql

I have a table in mysql like this (the id is primary key):

 id | name | age
 1 |  John | 46
 2 |       | 56
 3 | Jane  | 25 

Now I want to update the name only if this is empty. If the value is not empty it should duplicate the row with a new id else it should update the name.

I thought it could be done with an if-statement but it doesn't work.

if((select `name` from `table1` where `id` = 3) = '',
update `table1` set `name`='ally' where `id` = 3, 
insert into `table1` (`id`,`name`,`age`) values 
(4, 'ally', select `age` from `table1` where `id` = 3))

EDIT:

With Spencers answer I made it working using an if in the code. (However I would still like a way to do just a single mysql query).

db.set_database('database1')
cursor = db.cursor()

query = "select IF(CHAR_LENGTH(name)>0,1,0) from table1 where id = {0}".format(id)
cursor.execute(query)
val1 = cursor.fetchone()

if val1[0]:
    query = "INSERT INTO `table1` (`id`,`name`,`age`) SELECT {0},{1},`age` FROM `table1` WHERE `id` = {2}".format(new_id, name, id)
    cursor.execute(query)
else:
    query = "update `table1` set `name` = '{0}' where `id` = {1}".format(name, id)
    cursor.execute(query)

db.commit()
like image 279
user3605780 Avatar asked Mar 18 '26 20:03

user3605780


1 Answers

If you make like this :

select t.*, 
if( 
    EXISTS(select n.name from table1 n where n.id = 2 and NULLIF(n.name, '') is  null) , 
    'true', 
    'false' 
  ) from table1 t

if statement returns "true", becouse in your table exist row where id =2 and name is empty.

like this example, You can edit your query :

if(
     EXISTS(select n.name from table1 n where n.id = 3 and NULLIF(n.name, '') is  null),
     update `table1` set `name`='ally' where `id` = 3, 
    insert into `table1` (`id`,`name`,`age`) values 
  (4, 'ally', select `age` from `table1` where `id` = 3)
)
like image 59
EntGriff Avatar answered Mar 20 '26 11:03

EntGriff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!