Pergunta

I am trying to insert a row but only if it doesn't exist yet.

I've had a look through the forums and this syntax appears to be what I want:

INSERT INTO tblSites (site,homepage) VALUES ('A','www.a.com') 
WHERE NOT EXISTS (SELECT * FROM tblSites where homepage='www.a.com')

And I get a syntax error.

You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right
syntax to use near 'WHERE NOT EXISTS (SELECT * FROM tblSites where homepage='www.a.com')' 
at line 1

I've read around and everyone seems to be using this syntax, is it not available in the version I'm using or something? I've listed some other options below, but I'd like to understand why this isn't working for my own learning (and sanity).

Other methods I've looked at are:

1) REPLACE. In some others areas where I'm intending on using this query, I have millions of rows and duplicates are likely. I'd only want to use REPLACE if it was comparable in terms of efficiency to the above syntax. Any thoughts?

2) INSERT IGNORE. Might be worth using this, tblSites currently has (siteId,name,homepage). I could make homepage the id as it will be unique and then I believe this would work (?), but I'm also linking this table to tblContent (content on the sites) using tblContentSites (siteId,contentId) with composite key siteId+ContentId. I felt repeating an integer ID would be better than the homepage every time in that junction table. Also appreciate thoughts on this.

3) ON DUPLICATE KEY UPDATE - this seems to me to duplicate the rows but just give the new one a different ID, which is tantamount to duplicating data anyway and could cause my problems down the line. Am I misunderstanding the use of this? Do I have more flexibility of what to do after DUPLICATE KEY UPDATE?

Many thanks,

Drew

Foi útil?

Solução

Two steps:

  1. Add a unique constraint on the homepage column (if you have not already done so):

    ALTER TABLE `tblSites` ADD UNIQUE(`homepage`)
    
  2. Use INSERT IGNORE to only insert if that wouldn't cause a conflict.

    INSERT IGNORE INTO `tblSites` (`site`, `homepage`) VALUES ('A','www.a.com');
    
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top