1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

MySQL INSERT based on the uniqueness of a single field.

Discussion in 'PHP' started by Greg-J, Mar 31, 2008.

  1. #1
    A field in my table is labeled sha1. When I insert rows into this table I first need to check and make sure the sha1 field of the row I am inserting does not match the sha1 field of any existing row in the table.

    Is there a sql-only way of accomplishing this without having to first read the table into an array and compare it against my INSERT every INSERT?
    SEMrush
     
    Greg-J, Mar 31, 2008 IP
    SEMrush
  2. Silver89

    Silver89 Notable Member

    Messages:
    2,243
    Likes Received:
    72
    Best Answers:
    0
    Trophy Points:
    205
    #2
    If you set that field as the primary key you can use

    INSERT IGNORE INTO
     
    Silver89, Mar 31, 2008 IP
    Greg-J likes this.
  3. KalvinB

    KalvinB Peon

    Messages:
    2,787
    Likes Received:
    78
    Best Answers:
    0
    Trophy Points:
    0
    #3
    "SELECT 1 FROM table WHERE sha1 = value"

    If a row is returned then the value already exists.

    You should also give the column a unique key so MySQL won't insert rows with duplicate values for the sha1 column.

    If you just don't want the row inserted then you don't need to do the select. If you need to know if the key already exists then you have to do the select.
     
    KalvinB, Mar 31, 2008 IP
  4. Greg-J

    Greg-J I humbly return to you.

    Messages:
    1,844
    Likes Received:
    153
    Best Answers:
    0
    Trophy Points:
    135
    #4

    I think that's what I'm looking for. Thank you.
     
    Greg-J, Mar 31, 2008 IP
    Silver89 likes this.