Search code examples
mysqlif-statementidentifier

if else in mysql query


Let's say that I want to insert a record in a table. Each record has an ID (not unique) I want to check two columns (let say first and last name) and if these columns have already been in my table use that id, unless use another id for the new record.
In other words, I want to say IF the name is new assign a new ID else assign the id of that record. (Don't worry about the new id, assume that I have an original id for each record)
For example let say I have the following records in my table:

FirstName | LastName  | Location | Age ... | ID
John      | Smith     | Canada   | 12 ...  | 1234
John      | Smith     | US       | 21 ...  | 1234

And now I want to add another John Smith. So I want the same ID for the new record. While if I want to add Paul Smith, I want a new ID for that.


Solution

  • INSERT INTO YourTable (FirstName, LastName, Location, ID)
    SELECT new.FirstName, new.LastName, new.Location, IFNULL(present.ID, new.ID)
    FROM 
    (SELECT 'John' AS FirstName
     , 'Smith' AS LastName
     , 'UK' AS Location
     , 1111 AS ID) AS new
    LEFT OUTER JOIN YourTable AS present
    ON present.FirstName = new.FirstName
    AND present.LastName = new.LastName
    ORDER BY present.ID DESC
    LIMIT 1;
    

    SQLFiddle