search
HomeDatabaseSQL因为一条sql语句产生了自我怀疑!

因为一条sql语句产生了自我怀疑!

Dec 30, 2022 pm 04:34 PM
mysqldatabaserear end

 故事是这样开始的

在一个月黑风高的夜晚

现场报过来,本该打到新服务的流量,又走到了老服务,老服务的功能不健全,很可能会让现场的用户不能支付。 需要说明一点的是,任何一个从老服务改造到新服务的时候,都不是完全把流量切过去,都需要经过一点时间去验证。

比如我们按照地理位置去切,将北京的部分车场(是的,我们是做停车服务的),切到新服务,其他城市的车场在老服务

我们采用最简单的办法,就是靠一个字段type去控制(0和1)

看似简单,但是事怪就怪在这个字段上,这个控制字段是属于后来加到数据库字段的,而且没有对外去配置,都是通过运维手动去数据库配置的,且数据库字段默认值设置为1。

可总有几个车场时不时的从0就变成了1。。众所周知,一个新的字段不在mybatis xml和pojo出现,那么就不会有操作改掉

翻遍所有的服务,关乎这个表的都是update操作,update操作因为没有这个字段时打死也不会改这个type的

image.png

冷静下来想想,数据库默认字段为1,然后0都会变成1。没有1变成0的,可以肯定的是,先删除,又新增了,否则没有别的解释

经过一番查验,找到这样一堆代码(伪代码)

replace INTO `A` (
      park_id,
      xxxx,
      xxxx
    )
    SELECT
       park_id,
       xxxx,
       xxxx 
    FROM
    B 
    where b.park_id = #{parkId}复制代码

看到这里,心里嘿嘿一笑,破案了。。。。。

image.png

 replace INTO

是的,就是replace INTO搞得鬼,大家都知道,replace INTO和insert into的区别

1、replace into 首先尝试插入数据到表中, 如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据

2、如果表中无此数据,则插入新数据。

这就正好验证了上面的猜想,只有删除再添加,才会让type跟随数据库的默认值走

讲到这里不妨我们多了解一点这个,有人可能会问,replace是不是取代了insert和delete,毕竟是干了两件事

MySql手册关于replace into的算法:Mysql手册

MySQL uses the following algorithm for REPLACE (and LOAD DATA ... REPLACE):Try to insert the new row into the tableWhile the insertion fails because a duplicate-key error occurs for a primary key or unique index:Delete from the table the conflicting row that has the duplicate key valueTry again to insert the new row into the tableMySQL对REPLACE(和LOAD DATA…REPLACE)使用以下算法:

尝试将新行插入表中

当由于主键或唯一索引出现重复键错误而导致插入失败时:

从表中删除具有重复键值的冲突行

再次尝试将新行插入表中复制代码

先插入, 出错了再执行delete加insert. 如果自己用程序来做, 个人认为效率会低很多,另外这样写真的很搞人

这里推荐使用INSERT...ON DUPLICATE KEY UPDATE, 感觉很靠谱. replace的副作用:

  • replace每次要重新分配自增id;

  • replace中执行delete时, 在有外键的情况下会很麻烦;

  • 如果delete时定义的有触发器, 则会被执行;

  • 副作用也会被传播到replica slave

 总结

开发当中难免遇到奇奇怪怪的各种问题,有问题莫慌,冷静分析,你认为的不可能事件、你认为的计算机会发生错误,其实都是自己没有去完全理解到位,跟踪到位!!!【推荐学习:MySQL视频教程SQL视频教程

最后祝大家2023,少写bug,少加班,多涨薪

The above is the detailed content of 因为一条sql语句产生了自我怀疑!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
OLTP vs OLAP: What about big data?OLTP vs OLAP: What about big data?May 14, 2025 am 12:06 AM

OLTPandOLAParebothessentialforbigdata:OLTPhandlesreal-timetransactions,whileOLAPanalyzeslargedatasets.1)OLTPrequiresscalingwithtechnologieslikeNoSQLforbigdata,facingchallengesinconsistencyandsharding.2)OLAPusesHadoopandSparktoprocessbigdata,withsetup

What is Pattern Matching in SQL and How Does It Work?What is Pattern Matching in SQL and How Does It Work?May 13, 2025 pm 04:09 PM

PatternmatchinginSQLusestheLIKEoperatorandregularexpressionstosearchfortextpatterns.Itenablesflexibledataqueryingwithwildcardslike%and_,andregexforcomplexmatches.It'sversatilebutrequirescarefulusetoavoidperformanceissuesandoveruse.

Learning SQL: Understanding the Challenges and RewardsLearning SQL: Understanding the Challenges and RewardsMay 11, 2025 am 12:16 AM

Learning SQL requires mastering basic knowledge, core queries, complex JOIN operations and performance optimization. 1. Understand basic concepts such as tables, rows, and columns and different SQL dialects. 2. Proficient in using SELECT statements for querying. 3. Master the JOIN operation to obtain data from multiple tables. 4. Optimize query performance, avoid common errors, and use index and EXPLAIN commands.

SQL: Unveiling Its Purpose and FunctionalitySQL: Unveiling Its Purpose and FunctionalityMay 10, 2025 am 12:20 AM

The core concepts of SQL include CRUD operations, query optimization and performance improvement. 1) SQL is used to manage and operate relational databases and supports CRUD operations. 2) Query optimization involves the parsing, optimization and execution stages. 3) Performance improvement can be achieved through the use of indexes, avoiding SELECT*, selecting the appropriate JOIN type and pagination query.

SQL Security Best Practices: Protecting Your Database from VulnerabilitiesSQL Security Best Practices: Protecting Your Database from VulnerabilitiesMay 09, 2025 am 12:23 AM

Best practices to prevent SQL injection include: 1) using parameterized queries, 2) input validation, 3) minimum permission principle, and 4) using ORM framework. Through these methods, the database can be effectively protected from SQL injection and other security threats.

MySQL: A Practical Application of SQLMySQL: A Practical Application of SQLMay 08, 2025 am 12:12 AM

MySQL is popular because of its excellent performance and ease of use and maintenance. 1. Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2. Insert and query data: operate data through INSERTINTO and SELECT statements. 3. Optimize query: Use indexes and EXPLAIN statements to improve performance.

Comparing SQL and MySQL: Syntax and FeaturesComparing SQL and MySQL: Syntax and FeaturesMay 07, 2025 am 12:11 AM

The difference and connection between SQL and MySQL are as follows: 1.SQL is a standard language used to manage relational databases, and MySQL is a database management system based on SQL. 2.SQL provides basic CRUD operations, and MySQL adds stored procedures, triggers and other functions on this basis. 3. SQL syntax standardization, MySQL has been improved in some places, such as LIMIT used to limit the number of returned rows. 4. In the usage example, the query syntax of SQL and MySQL is slightly different, and the JOIN and GROUPBY of MySQL are more intuitive. 5. Common errors include syntax errors and performance issues. MySQL's EXPLAIN command can be used for debugging and optimizing queries.

SQL: A Guide for Beginners - Is It Easy to Learn?SQL: A Guide for Beginners - Is It Easy to Learn?May 06, 2025 am 12:06 AM

SQLiseasytolearnforbeginnersduetoitsstraightforwardsyntaxandbasicoperations,butmasteringitinvolvescomplexconcepts.1)StartwithsimplequerieslikeSELECT,INSERT,UPDATE,DELETE.2)PracticeregularlyusingplatformslikeLeetCodeorSQLFiddle.3)Understanddatabasedes

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

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),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools