分享一篇关于在mysql中对数据保存时如果存在就更新数据,否则就保存数据哦,很实用的,有需要的朋友可以参考一下。
//如果不存在,则插入新数据
代码如下 | 复制代码 |
$sql = "INSERT INTO {$ecs->table(‘cat_lang')} (cat_id,lang_id,cat_name,keywords,cat_desc) VALUES({$cat_id},{$k},'{$val['cat_name']}','{$val['keywords']}','{$val['cat_desc']}') ON DUPLICATE KEY UPDATE cat_name='{$val['cat_name']}',cat_desc='{$val['cat_desc']}',keywords='{$val['cat_desc']}'"; |
这里要注意的是:必须表主键唯一 。这里,这里我采用的是 分类id和语言id双主键机制。
key为唯一键或者主键
(1) key存在则替换,不存在则插入
代码如下 | 复制代码 |
replace into t_test | CREATE TABLE `t_test` ( `ikey` int(11) NOT NULL default '0', `value` varchar(21) NOT NULL default '', `icount` int(11) NOT NULL default '0', PRIMARY KEY (`ikey`) ) ENGINE=MyISAM DEFAULT CHARSET=gbk | |
对于这样一个表.当要记录ikey=1,value='a',icount=0时,由于不知道表里有没有ikey=1的项.我们可能会先,然后看有没有结果,如果有,则使用update进行更新.如果没有,则使用insert进行插入.
不过在大并发量的数据操作时,可能有时一个有主键的select查询都要用上2s,如果对旧数据不关心,减少不必要的操作显得犹为重要.
使用replace一个语句可以完成上面两个语句的功能,其语法与insert差不多.如上面的操作可以写为replace into t_test set ikey=1,value='a',icount=0;则表中有ikey为1时,先删除旧数据.然后插入新数据.否则直接插入数据.
(2) key存在则更新,不存在则插入
代码如下 | 复制代码 |
insert into .... on duplicate key update |
对于需要根据原记录进行操作的.如表中icount字段用于计数,当没有记录时,插入的value为0,当有记录时,value需要更新为value+1,这时replace就不能完成这个功能.使用insert则可以,其基本语法是insert into ... on duplicate key update...,如上述语句为
代码如下 | 复制代码 |
insert into t_test set ikey=1,value='a',value2=1 on duplicate key update value2=value2+1; |
如果表中有多个唯一索引,如对value字段加个unique key.这时表中有ikey和value两个唯一索引,replace会把所有与其唯一索引值相同的数据项删除,再插入新记录.如表中有两个记录
代码如下 | 复制代码 |
+------+-------+--------+ | ikey | value | icount | +------+-------+--------+ | 2 | a | 10 | | 1 | b | 40 | +------+-------+--------+ 则replace into t_test set ikey=1,value='a',icount=0;会把表中的两条记录都删除,然后插入新记录. 而insert into t_test set ikey=1,value='a',icount=0 on duplicate key update icount=icount+1则只更新一条记录.其效果相当于update t_test set icount=icount+1 where ikey=1 or value='a' limit 1; |

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),