我使用的是mysql 5.6。
我有以下sql:
update booking set status=1 where id in(
select VD.b_id from tableA VD inner join tableB V on VD.v_id=V.id
where V.type > 2 and V.status not in (1,2) and VD.b_id>0
and abs(VD.amount) - abs(VD.l_amount) > 1)
它的解释是:
<table border="1">
<tr>
<th>select_type</th>
<th>table</th>
<th>type</th>
<th>possible_keys</th>
<th>key</th>
<th>key_len</th>
<th>ref</th>
<th>rows</th>
<th>Extra</th>
</tr>
<tr>
<td>PRIMARY</td>
<td>booking</td>
<td>index</td>
<td></td>
<td>PRIMARY</td>
<td>4</td>
<td></td>
<td>152070</td>
<td>Using where</td>
</tr>
<tr>
<td>DEPENDENT SUBQUERY</td>
<td>V</td>
<td>range</td>
<td>PRIMARY,FK_VOUCHER_TYPE_VTID</td>
<td>FK_VOUCHER_TYPE_VTID</td>
<td>4</td>
<td></td>
<td>79652</td>
<td>Using index condition; Using where</td>
</tr>
<tr>
<td>DEPENDENT SUBQUERY</td>
<td>VD</td>
<td>ref</td>
<td>FK_VOUCHER_DETAIL_VID</td>
<td>FK_VOUCHER_DETAIL_VID</td>
<td>4</td>
<td>CDS.V.ID</td>
<td>1</td>
<td>Using where</td>
</tr>
</table>
&#13;
但是,这个更新语句太慢了,它一直执行到mysql超时(10分钟)。
预订具有自动增量的PK ID,tableA具有自动增量的PK ID和tableB的外键v_id引用ID。
tableA的b_id来自预订ID,但预订和tableA之间没有外键。如果我只运行子查询
选择VD.id ...
,它只返回5行。
但如果我使用select *来封装选择VD.id,就像下一个:
update booking set status=1 where id in(
select * from (
select VD.b_id from tableA VD inner join tableB V on VD.v_id=V.id
where V.type > 2 and V.status not in (1,2) and VD.b_id>0
and abs(VD.amount) - abs(VD.l_amount) > 1) t
)
然后这个更新语句只需要2秒钟。
它的解释是:
<table border="1">
<tr>
<th>select_type</th>
<th>table</th>
<th>type</th>
<th>possible_keys</th>
<th>key</th>
<th>key_len</th>
<th>ref</th>
<th>rows</th>
<th>Extra</th>
</tr>
<tr>
<td>PRIMARY</td>
<td>booking</td>
<td>index</td>
<td></td>
<td>PRIMARY</td>
<td>4</td>
<td></td>
<td>152070</td>
<td>Using where</td>
</tr>
<tr>
<td>DEPENDENT SUBQUERY</td>
<td><derived3></td>
<td>index_subquery</td>
<td><auto_key0></td>
<td><auto_key0></td>
<td>4</td>
<td>func</td>
<td>7965</td>
<td>Using index</td>
</tr>
<tr>
<td>DERIVED</td>
<td>V</td>
<td>ALL</td>
<td>PRIMARY,FK_VOUCHER_TYPE_VTID</td>
<td></td>
<td></td>
<td></td>
<td>217193</td>
<td>Using where</td>
</tr>
<tr>
<td>DERIVED</td>
<td>VD</td>
<td>ref</td>
<td>FK_VOUCHER_DETAIL_VID</td>
<td>FK_VOUCHER_DETAIL_VID</td>
<td>4</td>
<td>CDS.V.ID</td>
<td>1</td>
<td>Using where</td>
</tr>
</table>
&#13;
OM / WwyLB.png