cnblogs/dcrenl/mysql 无数据插入,有数据更新.html
2024-09-24 12:43:01 +08:00

25 lines
2.5 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<p>mysql的语法与sql&nbsp;server有很多不同sql server执行插入更新时可以update后使用if判断返回的@@rowcount值然后确定是否插入mysql在语句中无法使用类似sql&nbsp;server的@@rowcount但是有另外一些方式也能达到无数据插入有数据更新的目的</p>
<p>&nbsp;</p>
<p><strong>1、REPLACE相当于如果数据存在先按主键删除原记录后再添加记录新记录此方式会更新索引</strong></p>
<p>&nbsp;</p>
<div class="cnblogs_code">
<pre><span style="color: #ff00ff;">REPLACE</span> <span style="color: #0000ff;">INTO</span><span style="color: #000000;"> t_param (param_name,param_value)
</span><span style="color: #0000ff;">select</span> #{paramName}, #{paramValue}</pre>
</div>
<p>&nbsp;</p>
<p><strong>2、ON DUPLICATE KEY UPDATE&nbsp;先更新数据如果数据不存在时进行insert</strong></p>
<p>&nbsp;</p>
<div class="cnblogs_code">
<pre><span style="color: #0000ff;">insert</span> <span style="color: #0000ff;">into</span> t_param (param_name, param_value) <span style="color: #0000ff;">values</span><span style="color: #000000;"> (#{paramName}, #{paramValue})
</span><span style="color: #0000ff;">ON</span> DUPLICATE <span style="color: #0000ff;">KEY</span>
<span style="color: #0000ff;">UPDATE</span> param_name <span style="color: #808080;">=</span> #{paramName},param_value <span style="color: #808080;">=</span> #{paramValue}</pre>
</div>
<p>&nbsp;</p>
<p><strong>3、判断需要插入的数据是否存在如果不存在时就插入否则直接执行更新</strong></p>
<p>&nbsp;</p>
<div class="cnblogs_code">
<pre><span style="color: #0000ff;">INSERT</span> <span style="color: #0000ff;">INTO</span> t_param (param_name,param_value) <span style="color: #0000ff;">SELECT</span> #{paramName},#{paramValue} <span style="color: #0000ff;">FROM</span><span style="color: #000000;"> DUAL
</span><span style="color: #0000ff;">WHERE</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">EXISTS</span> (<span style="color: #0000ff;">SELECT</span> param_value <span style="color: #0000ff;">FROM</span> t_param <span style="color: #0000ff;">WHERE</span> param_name <span style="color: #808080;">=</span><span style="color: #000000;"> #{paramName});
</span><span style="color: #0000ff;">UPDATE</span> t_param <span style="color: #0000ff;">SET</span> param_value <span style="color: #808080;">=</span> #{paramValue} <span style="color: #0000ff;">WHERE</span> param_name <span style="color: #808080;">=</span> #{paramName}</pre>
</div>
<p>&nbsp;</p>