开发者

Unique constraint, how to avoid duplicates

According to my previous Query that pos开发者_JS百科t i have a table that looks like this:

|| *nid* || *language* ||
|| 8 || Chinese ||
|| 8 || Portuguese ||
|| 8 || German |

In which 'nid' and 'language' have a unique constraint.

With this setup how can i make sure that the there wont be any duplicate when i try to insert a new row ?

EDITED

I am guessing I should try to make a query such as:

SELECT * FROM lang WHERE nid = $nid AND language = $lang

If this return FALSE then i know i can now insert my data. Is this correct ?


Enforce the unique constraint by creating a unique key:

ALTER TABLE the_table
ADD UNIQUE INDEX nid_language_unique (nid, language);

This constraint forbid two rows having the same nid and language.

Any query attempting to violate the constraint will fail.

As you want to ignore errors (and still abort the query), you can use INSERT IGNORE and UPDATE IGNORE:

INSERT IGNORE INTO the_table (nid, language) VALUES (8, 'Chinese')
/* row not inserted and no error */


If you have actually established a unique constraint in the database then MySQL will not let you insert the second row. The statement will raise an exception. You can trap and ignore that in your code. If you're not interested in whether the row was added or not, you can use the IGNORE keyward in the MySQL INSERT INTO command and the row will either be added (if not there) or the command will complete without an error.


SELECT nid, language FROM lang WHERE nid = $nid AND language = $lang

If this return FALSE then i know i can now insert my data. Is this correct ?

Yes, but you need to write:

$nid = mysql_real_escape_string($_POST['nid']);
$lang = mysql_real_escape_string($_POST['lang']);
$query = SELECT nid, language FROM lang WHERE nid = '$nid' AND language = '$lang'
// notice the quotes                                ^    ^                ^     ^

If you forget these your query give an error (and be at risk from SQL-injection).

If you have a unique constraint, you can just go ahead and insert the data, because MySQL will do the above test for you.


You can use a counter in your code (not SQL, but the one you use to use SQL, like PHP, or else)

You can use MySQL max function and add one (like max(nid)+1 (but don't remember about MySQL's max function))

You can use a random number with 10 characters (so you'd would have a really really low risk to go into an error)

I used the first and last way many times.

And if you want to be sure that you won't have a duplicate, use the solutions from your last posts. Stuff like UNIQUE constraint will prevent you to insert twice the same nid or language (thus, if you don't handle it, your program will crash).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜