Home Database Mysql Tutorial 浅谈unique列上插入重复值的MySQL解决方案

浅谈unique列上插入重复值的MySQL解决方案

Jun 07, 2016 pm 04:09 PM
mysql unique insert solution repeat

本文的unique列上插入重复值解决方案,主要基于MySQL平台。通过这些,可以做到一些新的功能和应用。希望本文能对大家有所帮助。 当unique列在一个UNIQUE键上插入包含重复值的记录时,我们可以控制MySQL如何处理这种情况:使用IGNORE关键字或者ON DUPLICATE K

本文的unique列上插入重复值解决方案,主要基于MySQL平台。通过这些,可以做到一些新的功能和应用。希望本文能对大家有所帮助。

当unique列在一个UNIQUE键上插入包含重复值的记录时,我们可以控制MySQL如何处理这种情况:使用IGNORE关键字或者ON DUPLICATE KEY UPDATE子句跳过INSERT、中断操作或者更新旧记录为新值。

<ol class="dp-sql">
<li class="alt"><span><span>mysql> </span><span class="keyword">create</span><span> </span><span class="keyword">table</span><span> menus(id tinyint(4) </span><span class="op">not</span><span> </span><span class="op">null</span><span> auto_increment,  </span></span></li>
<li class="">
<span>   -> label </span><span class="keyword">varchar</span><span>(10) </span><span class="op">null</span><span>,url </span><span class="keyword">varchar</span><span>(20) </span><span class="op">null</span><span>,</span><span class="keyword">unique</span><span> </span><span class="keyword">key</span><span>(id));  </span>
</li>
<li class="alt">
<span>Query OK, 0 </span><span class="keyword">rows</span><span> affected (0.13 sec)  </span>
</li>
<li class="">
<span>mysql> </span><span class="keyword">insert</span><span> </span><span class="keyword">into</span><span> menus(label,url) </span><span class="keyword">values</span><span>(</span><span class="string">'Home'</span><span>,</span><span class="string">'home.html'</span><span>);  </span>
</li>
<li class="alt"><span>Query OK, 1 row affected (0.06 sec)  </span></li>
<li class="">
<span>mysql> </span><span class="keyword">insert</span><span> </span><span class="keyword">into</span><span> menus(label,url) </span><span class="keyword">values</span><span>(</span><span class="string">'About us'</span><span>,</span><span class="string">'aboutus.html'</span><span>);  </span>
</li>
<li class="alt"><span>Query OK, 1 row affected (0.05 sec)  </span></li>
<li class="">
<span>mysql> </span><span class="keyword">insert</span><span> </span><span class="keyword">into</span><span> menus(label,url) </span><span class="keyword">values</span><span>(</span><span class="string">'Services'</span><span>,</span><span class="string">'services.html'</span><span>);  </span>
</li>
<li class="alt"><span>Query OK, 1 row affected (0.05 sec)  </span></li>
<li class="">
<span>mysql> </span><span class="keyword">insert</span><span> </span><span class="keyword">into</span><span> menus(label,url) </span><span class="keyword">values</span><span>(</span><span class="string">'Feedback'</span><span>,</span><span class="string">'feedback.html'</span><span>);  </span>
</li>
<li class="alt"><span>Query OK, 1 row affected (0.05 sec) </span></li>
</ol>
Copy after login
<ol class="dp-sql">
<li class="alt"><span><span>mysql> </span><span class="keyword"><strong><font color="#006699">select</font></strong></span><span> * </span><span class="keyword"><strong><font color="#006699">from</font></strong></span><span> menus;  </span></span></li>
<li class="">
<span>+</span><span class="comment"><font color="#008200">----+----------+---------------+ </font></span><span> </span>
</li>
<li class="alt"><span>| id | label   | url          |  </span></li>
<li class="">
<span>+</span><span class="comment"><font color="#008200">----+----------+---------------+ </font></span><span> </span>
</li>
<li class="alt"><span>| 1 | Home    | home.html    |  </span></li>
<li class=""><span>| 2 | About us | aboutus.html |  </span></li>
<li class="alt"><span>| 3 | Services | services.html |  </span></li>
<li class=""><span>| 4 | Feedback | feedback.html |  </span></li>
<li class="alt">
<span>+</span><span class="comment"><font color="#008200">----+----------+---------------+ </font></span><span> </span>
</li>
<li class="">
<span>4 </span><span class="keyword"><strong><font color="#006699">rows</font></strong></span><span> </span><span class="op"><font color="#808080">in</font></span><span> </span><span class="keyword"><strong><font color="#006699">set</font></strong></span><span> (0.00 sec) </span>
</li>
</ol>
Copy after login

如果现在在unique列插入一条违背唯一约束的记录,MySQL会中断操作,提示出错:

<ol class="dp-sql">
<li class="alt"><span><span>mysql> </span><span class="keyword"><strong><font color="#006699">insert</font></strong></span><span> </span><span class="keyword"><strong><font color="#006699">into</font></strong></span><span> menus(id,label,url) </span><span class="keyword"><strong><font color="#006699">values</font></strong></span><span>(4,</span><span class="string"><font color="#0000ff">'Contact us'</font></span><span>,</span><span class="string"><font color="#0000ff">'contactus.html'</font></span><span>);  </span></span></li>
<li class="">
<span>ERROR 1062 (23000): Duplicate entry </span><span class="string"><font color="#0000ff">'4'</font></span><span> </span><span class="keyword"><strong><font color="#006699">for</font></strong></span><span> </span><span class="keyword"><strong><font color="#006699">key</font></strong></span><span> </span><span class="string"><font color="#0000ff">'id'</font></span><span> </span>
</li>
</ol>
Copy after login

在前面的INSERT语句添加IGNORE关键字时,如果认为语句违背了唯一约束,MySQL甚至不会尝试去执行这条语句,因此,下面的语句不会返回错误:

<ol class="dp-sql">
<li class="alt"><span><span>mysql> </span><span class="keyword"><strong><font color="#006699">insert</font></strong></span><span> </span><span class="keyword"><strong><font color="#006699">ignore</font></strong></span><span> </span><span class="keyword"><strong><font color="#006699">into</font></strong></span><span> menus(id,label,url) </span><span class="keyword"><strong><font color="#006699">values</font></strong></span><span>(4,</span><span class="string"><font color="#0000ff">'Contact us'</font></span><span>,</span><span class="string"><font color="#0000ff">'contactus.html'</font></span><span>);  </span></span></li>
<li class="">
<span>Query OK, 0 </span><span class="keyword"><strong><font color="#006699">rows</font></strong></span><span> affected (0.00 sec)  </span>
</li>
<li class="alt">
<span>mysql> </span><span class="keyword"><strong><font color="#006699">select</font></strong></span><span> * </span><span class="keyword"><strong><font color="#006699">from</font></strong></span><span> menus;  </span>
</li>
<li class="">
<span>+</span><span class="comment"><font color="#008200">----+----------+---------------+ </font></span><span> </span>
</li>
<li class="alt"><span>| id | label   | url          |  </span></li>
<li class="">
<span>+</span><span class="comment"><font color="#008200">----+----------+---------------+ </font></span><span> </span>
</li>
<li class="alt"><span>| 1 | Home    | home.html    |  </span></li>
<li class=""><span>| 2 | About us | aboutus.html |  </span></li>
<li class="alt"><span>| 3 | Services | services.html |  </span></li>
<li class=""><span>| 4 | Feedback | feedback.html |  </span></li>
<li class="alt">
<span>+</span><span class="comment"><font color="#008200">----+----------+---------------+ </font></span><span> </span>
</li>
<li class="">
<span>4 </span><span class="keyword"><strong><font color="#006699">rows</font></strong></span><span> </span><span class="op"><font color="#808080">in</font></span><span> </span><span class="keyword"><strong><font color="#006699">set</font></strong></span><span> (0.00 sec) </span>
</li>
</ol>
Copy after login

当有很多的INSERT语句需要被顺序地执行时,IGNORE关键字就使操作变得很方便。使用它可以保证不管哪一个INSERT包含了重复的键值,MySQL都回跳过它(而不是放弃全部操作)。

在这种情况下,我们还可以通过添加MySQL4.1新增加的ON DUPLICATE KEY UPDATE子句,使MySQL自动把INSERT操作转换为UPDATE操作。这个子句必须具有需要更新的字段列表,这个列表和UPDATE语句使用的列表相同。

<ol class="dp-sql">
<li class="alt"><span><span>mysql> </span><span class="keyword"><strong><font color="#006699">insert</font></strong></span><span> </span><span class="keyword"><strong><font color="#006699">into</font></strong></span><span> menus(id,label,url) </span><span class="keyword"><strong><font color="#006699">values</font></strong></span><span>(4,</span><span class="string"><font color="#0000ff">'Contact us'</font></span><span>,</span><span class="string"><font color="#0000ff">'contactus.html'</font></span><span>)  </span></span></li>
<li class="">
<span>   -> </span><span class="keyword"><strong><font color="#006699">on</font></strong></span><span> duplicate </span><span class="keyword"><strong><font color="#006699">key</font></strong></span><span> </span><span class="keyword"><strong><font color="#006699">update</font></strong></span><span> label=</span><span class="string"><font color="#0000ff">'Contact us'</font></span><span>,url=</span><span class="string"><font color="#0000ff">'contactus.html'</font></span><span>;  </span>
</li>
<li class="alt">
<span>Query OK, 2 </span><span class="keyword"><strong><font color="#006699">rows</font></strong></span><span> affected (0.05 sec) </span>
</li>
</ol>
Copy after login

在这种情况下,如果MySQL发现表已经包含具有相同唯一键的记录,它会自动更新旧的记录为ON DUPLICATE KEY UPDATE从句中指定的新值:

<ol class="dp-sql">
<li class="alt"><span><span>mysql> </span><span class="keyword"><strong><font color="#006699">select</font></strong></span><span> * </span><span class="keyword"><strong><font color="#006699">from</font></strong></span><span> menus;  </span></span></li>
<li class="">
<span>+</span><span class="comment"><font color="#008200">----+------------+----------------+ </font></span><span> </span>
</li>
<li class="alt"><span>| id | label     | url           |  </span></li>
<li class="">
<span>+</span><span class="comment"><font color="#008200">----+------------+----------------+ </font></span><span> </span>
</li>
<li class="alt"><span>| 1 | Home      | home.html     |  </span></li>
<li class=""><span>| 2 | About us  | aboutus.html  |  </span></li>
<li class="alt"><span>| 3 | Services  | services.html |  </span></li>
<li class=""><span>| 4 | Contact us | contactus.html |  </span></li>
<li class="alt">
<span>+</span><span class="comment"><font color="#008200">----+------------+----------------+ </font></span><span> </span>
</li>
<li class="">
<span>4 </span><span class="keyword"><strong><font color="#006699">rows</font></strong></span><span> </span><span class="op"><font color="#808080">in</font></span><span> </span><span class="keyword"><strong><font color="#006699">set</font></strong></span><span> (0.01 sec) </span>
</li>
</ol>
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP's big data structure processing skills PHP's big data structure processing skills May 08, 2024 am 10:24 AM

Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Jun 03, 2024 pm 01:25 PM

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the &quot;MySQL Native Password&quot; plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

Java framework security vulnerability analysis and solutions Java framework security vulnerability analysis and solutions Jun 04, 2024 pm 06:34 PM

Analysis of Java framework security vulnerabilities shows that XSS, SQL injection and SSRF are common vulnerabilities. Solutions include: using security framework versions, input validation, output encoding, preventing SQL injection, using CSRF protection, disabling unnecessary features, setting security headers. In actual cases, the ApacheStruts2OGNL injection vulnerability can be solved by updating the framework version and using the OGNL expression checking tool.

See all articles