<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>replace into &#8211; LPC影子技术分享</title>
	<atom:link href="https://www.mudbest.com/tag/replace-into/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.mudbest.com</link>
	<description>行影不离,忘之却步.</description>
	<lastBuildDate>Mon, 01 Oct 2012 09:49:23 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.2</generator>
	<item>
		<title>MySQL replace into 用法（insert into 的增强版）</title>
		<link>https://www.mudbest.com/mysql-replace-into-%e7%94%a8%e6%b3%95%ef%bc%88insert-into-%e7%9a%84%e5%a2%9e%e5%bc%ba%e7%89%88%ef%bc%89/</link>
		
		<dc:creator><![CDATA[hkshadow]]></dc:creator>
		<pubDate>Fri, 05 Aug 2011 17:45:34 +0000</pubDate>
				<category><![CDATA[Mysql]]></category>
		<category><![CDATA[replace into]]></category>
		<guid isPermaLink="false">http://www.mudbest.com/?p=725</guid>

					<description><![CDATA[在向表中插入数据的时候，经常遇到这样的情况：1. 首先判断数据是否存在； 2. 如果不存在，则插入；3.如果存 ... <a title="MySQL replace into 用法（insert into 的增强版）" class="read-more" href="https://www.mudbest.com/mysql-replace-into-%e7%94%a8%e6%b3%95%ef%bc%88insert-into-%e7%9a%84%e5%a2%9e%e5%bc%ba%e7%89%88%ef%bc%89/" aria-label="阅读 MySQL replace into 用法（insert into 的增强版）">阅读更多</a>]]></description>
										<content:encoded><![CDATA[<p>在向表中插入数据的时候，经常遇到这样的情况：1. 首先判断数据是否存在； 2. 如果不存在，则插入；3.如果存在，则更新。 </p>
<p>在 SQL Server 中可以这样处理： </p>
<pre class="brush: sql; title: ; notranslate">
 if not exists (select 1 from t where id = 1) insert into t(id, update_time) values(1, getdate()) else update t set update_time = getdate() where id = 1
</pre>
<p><span id="more-725"></span>那么 MySQL 中如何实现这样的逻辑呢？别着急！MySQL 中有更简单的方法： replace into </p>
<pre class="brush: sql; title: ; notranslate">
replace into t(id, update_time) values(1, now());
</pre>
<p>或 </p>
<pre class="brush: php; title: ; notranslate">
replace into t(id, update_time) select 1, now();
</pre>
<p>replace into 跟 insert 功能类似，不同点在于：replace into 首先尝试插入数据到表中，</p>
<p>1. 如果发现表中已经有此行数据（根据主键或者唯一索引判断）则先删除此行数据，然后插入新的数据。<br />
2. 否则，直接插入新数据。 </p>
<p>要注意的是：插入数据的表必须有主键或者是唯一索引！否则的话，replace into 会直接插入数据，这将导致表中出现重复的数据。 </p>
<p>MySQL replace into 有三种形式：<br />
1. replace into tbl_name(col_name, &#8230;) values(&#8230;)<br />
2. replace into tbl_name(col_name, &#8230;) select &#8230;<br />
3. replace into tbl_name set col_name=value, &#8230;<br />
前两种形式用的多些。其中 “into” 关键字可以省略，不过最好加上 “into”，这样意思更加直观。另外，对于那些没有给予值的列，MySQL 将自动为这些列赋上默认值。 </p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
