English 中文(简体)
当 UIQUE KEY 被违反时, 获取一行的代号
原标题:Get the id of a row when UNIQUE KEY is violated
  • 时间:2012-05-24 10:13:55
  •  标签:
  • mysql
  • sql

我有一张表格user 。它有列 id email

使用表

id | email
1  | [email protected]
2  | [email protected]

The id is a PRIMARY KEY AUTO_INCREMENT and the email is an UNIQUE KEY. When I insert a new row in the table and there is a DUPLICATE KEY exception thrown. I want to fetch the id on which the DUPLICATE KEY exception was thrown.

现在,我正在做这个...

BEGIN
DECLARE EXIT HANDLER FOR 1062
    BEGIN
        SELECT id
        INTO id
        FROM user
        WHERE email =  [email protected] ;
    END;
    INSERT INTO user
    (email)
    VALUES
    ( [email protected] );

SELECT LAST_INSERT_ID() INTO id;
END;

我想知道是否有更好的办法做到这一点。这就是为了避免再次扫描表格,获取它已经扫描过的身份,以检查电子邮件的独特性。

最佳回答

使用 < a href=" "http://dev.mysql.com/doc/refman/5.1/en/ Indeplain-on-dupreplicate.html" rel="nofollow"\ code >INSTERT... 在 DUPLICATE KEY UPDATE 上,然后 < a href=""http://dev.mysql.com/doc/en/getting-unique-id.html" rel="nofolfollow" 使自动加速的id和往常一样 :

如果一个表格包含 AUTO_INCRONT 专栏和 < a href="http://dev.mysql.com/doc/refman/5.1/en/ information-supids.html#dev.mysql.doc/doc/refrdex_dref="http://dev. mysql.com/code/code/rfman/5.1/en/formation-supid_comids.html_supid_l-adex-id > rel="Nofol="LA\code>LST_INSERT_ID_ID_ID() 。

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3;
问题回答

在通过 UNIQUE KEY 扫描时,使用了 UNIQUE KEY ,因此扫描速度相当快。

您不想在额外的 select 查询中自己检查是否有价值存在吗?





相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...