2

桌子:

  • foreign_id_1
  • foreign_id_2
  • 整数
  • 日期1
  • 日期2
  • 主要(foreign_id_1,foreign_id_2)

询问:delete from table where (foreign_id_1 = ? or foreign_id_2 = ?) and date2 < ?

没有日期查询大约需要 40 秒。那太高了:(日期更长了..

选项包括:

  • create另一个表insert select,然后rename
  • 使用限制并多次运行查询
  • 拆分查询foreign_id_1然后运行foreign_id_2
  • 使用选择然后按单行删除

有没有更快的方法?


mysql> explain select * from compatibility where user_id = 193 or person_id = 193 \G
           id: 1
  select_type: SIMPLE
        table: compatibility
         type: index_merge
possible_keys: PRIMARY,compatibility_person_id_user_id
          key: PRIMARY,compatibility_person_id_user_id
      key_len: 4,4
          ref: NULL
         rows: 2
        Extra: Using union(PRIMARY,compatibility_person_id_user_id); Using where
1 row in set (0.00 sec)

mysql> explain select * from compatibility where (user_id = 193 or person_id = 193) and updated_at < '2010-12-02 22:55:33' \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: compatibility
         type: index_merge
possible_keys: PRIMARY,compatibility_person_id_user_id
          key: PRIMARY,compatibility_person_id_user_id
      key_len: 4,4
          ref: NULL
         rows: 2
        Extra: Using union(PRIMARY,compatibility_person_id_user_id); Using where
1 row in set (0.00 sec)
4

2 回答 2

2

有一个OR在你的WHERE使 MySQL 不愿意(如果不是完全拒绝)在你的user_id和/或person_id字段上使用索引(如果有的话 - 显示CREATE TABLE将表明是否有)。

如果您可以添加索引(或修改现有索引,因为我正在考虑复合索引),我可能会添加两个:

ALTER TABLE compatibility 
ADD INDEX user_id_updated_at (user_id, updated_at),
ADD INDEX persona_id_updated_at (person_id, updated_at);

相应地,假设DELETE 不必以原子方式删除行(即在同一时刻发生)。

DELETE FROM compatibility WHERE user_id = 193 AND updated_at < '2010-12-02 22:55:33';

DELETE FROM compatibility WHERE person_id = 193 AND updated_at < '2010-12-02 22:55:33';
于 2010-12-02T21:07:02.313 回答
0

到目前为止,数据量为 40M (+33%),并且还在快速增长。所以我开始寻找其他一些无 sql 的解决方案。

谢谢。

于 2010-12-04T04:43:05.500 回答