简体   繁体   中英

Loop thru an array and insert into or update a column based on empty values in the column - MySQL

I will have user input content(email addresses) that I'll be introducing into a database(MySQL) based on what project those emails are from. I have 1 email table for all of the projects, which aren't that many(about 20), each project will have a separate column. Some emails are going to be removed eventually and some fields in some rows will be marked as empty or null.

Most of the time the emails will come in bulk(so to speak) so I'll have to loop thru an array of emails and for every value, introduce that value into whatever project that email belongs to. So far so good, that's already done.

However, as I said, some emails are going to be removed. I want to replace empty fields with email addresses and if no empty fields are found insert the emails into the column.

Emails will come in bulks so I'll loop thru the array and for every value proceed to execute an insert or update statement depending on the empty fields.

Long story short I have this code:

SELECT column_name 
FROM table_name 
    CASE 
      WHEN column_name='' OR column_name IS NULL 
      THEN 
      UPDATE SET column_name='new_value' 
      WHERE column_name='' OR column_name IS NULL
      ELSE INSERT INTO table_name(column_name) VALUES ('new_value')
    END

Which doesn't work. I'm 100% sure I messed up the syntax somewhere, however the MySQL manual is not much of a help. Some pages suggest using CASE, some suggest using IF.

If somebody could take a look at it and give me some pointers, I'd be very grateful.

I'm using PHP for this.

If anything is unclear in my explanation(I have a habit of doing that), please let me know.


Looking at the IF/ELSEIF from MySQL manual:

IF search_condition THEN statement_list
    [ELSEIF search_condition THEN statement_list] ...
    [ELSE statement_list]
END IF

My new and no so improved code should look like this:

SELECT column_name 
FROM table_name 
IF column_name='' OR column_name IS NULL 
THEN UPDATE SET column_name='new_value' WHERE column_name='' OR column_name IS NULL 
ELSE INSERT INTO table_name (column_name) VALUES ('new_value) 
END IF

Which of course does not work.

If column_name is a PRIMARY KEY or UNIQUE INDEX you can use INSERT.. ON DUPLICATE KEY UPDATE :

INSERT INTO table_name(column_name) VALUES ('new_value')
ON DUPLICATE KEY UPDATE column_name = 'new_value' 

From the docs:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed.

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