Results 1 to 6 of 6
  1. #1
    Join Date
    Oct 2004
    Location
    In cousin's house
    Posts
    303

    Unanswered: insert update statement to avoid duplicate

    hi,
    i have a table below and corresponding field.
    table1
    code // it's a unique field.
    des // varchar

    insert into table1(code,des) values('001','description') on duplicate key update des = 'new description';
    the sql above is used to insert data but if already exist it execute update my problem is , what if my field code is not unique. How to execute a insert / update sql.

    Anyone can help me.
    Popskie

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Quote Originally Posted by popskie
    what if my field code is not unique.
    well, you started out saying that it is unique

    anyhow, the mysql manual says that if it is not unique, only one row will be updated

    you should probably run a few queries on a test table to become familiar with how it works
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  3. #3
    Join Date
    Oct 2004
    Location
    In cousin's house
    Posts
    303
    Is their any other way beside on duplicate key. Ok i'll explain to you clearly.
    My scenario is there is a insert / update procudere with two filtering expression.

    ex.
    if id and code not exist.
    insert into table1(id,code,name)values(value1,value2,value3)
    else
    update table1 set name = value3 where id =value1 and code = value2


    Is this posible in mysql with only a single shot and take this two statement execute to the server.

  4. #4
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    define your key with two fields
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  5. #5
    Join Date
    Oct 2004
    Location
    In cousin's house
    Posts
    303
    ok thanks r937. I thought mysql primary has only 1 field.

  6. #6
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    that's right, keys can have more than one column

    PRIMARY KEY (index_col_name,...)

    the "dot dot dot" is the secret
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •