Insert into SQL if record does not exist

Asked

Viewed 49 times

0

I have the following PHP function that adds a row to the table:

$idmusica = $_GET['idmusica'];
$queryvota=("
    INSERT INTO euk_sugestoes_votos (idusuario, idmusica)
    VALUES ($userid, $idmusica)
    ");

The table has this structure:

id | idusuario | idmusica

But I wanted that before inserting, he checked if this line with idusuario and idmusica already exists. If it already exists, should ignore, otherwise it inserts.

How can I make this check?

Thank you!

  • I don’t know if this is your case, but be careful if you are using mysql_query as it is obsolete in the current version.

1 answer

2


There is, create a index unique for the 2 columns id_usuario and idmusica and instead of using INSERT INTO use the REPLACE INTO, basically it does this automatic check.

The index unique would already solve the problem, but would return an error.

And switching to REPLACE as it will not update any field, it will just ignore the record.

But the REPLACE will change your primary key if it is AUTO_INCREMENT.

Another way, also keeping one index unique is to use the INSERR IGNORE, then it would be like this, for example:

INSERT IGNORE INTO euk_sugestoes_votos(idusuario,idmusica)VALUES(1,2);

To create the index, follow the command:

CREATE UNIQUE INDEX idx_unique_idusuario_idmusica
    ON euk_sugestoes_votos (idusuario,idmusica);
  • but with the Unique index it will not allow to have 2 equal record right? is that you need to have for example: idusuario=1 and idmusica=2; idusuario=1 and idmusica=1; idusuario=2 and idmusica=2...etc

  • Exactly, it will never let repeat the two together idusuario and idmusica. not separated, you may have n idusuario(1) and n idmusica(1) but never repeated

  • basic question, how do I create the Unique index pros 2?

  • @Leandromarzullo edited the answer with the index creation script

  • SHOW! It worked fine, thanks!

  • Good @Leandromarzullo for nothing! ;)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.