开发者

mysql unique field

i have table with unique field uniq_field. what method adding is better- first ch开发者_开发技巧eck if record with unique value exists or simply add record and mysql will check by himself?


it depends on the action you gonna take in case of duplicate
possible solutions can be shown in such a pseudo code

switch action
    case "do nothing":
        INSERT IGNORE
    case "delete existing then add new one":
        REPLACE INTO
    case "update existing":
        ON DUPLICATE UPDATE
    default:
        select first and then apply necessary logic


it depends on how you want to handle it in your code.

If you just want to make sure that element exists, you can do what's called a insert - on duplicate key update - that means that the row gets replaced if it's already present - but if it's not, it gets updated.

More on that topic here: http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html


Well for this table

+--------+---------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| id     | int(11) | NO   | PRI | 0       |       |
| unique | int(11) | NO   | UNI | NULL    |       |
+--------+---------+------+-----+---------+-------+

This code returns false

$result = mysql_query("insert into tab1 values(1, 1), (2, 1)");

echo ($result)?($result):"false";

While this code returns 1

$result = mysql_query("insert into tab1 values(1, 1), (2, 2)");

echo ($result)?($result):"false";

It seems that if you want to display message, then you should check for values in you database and display an error. If you don't want to display what actually caused and error then you can directly query.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜