mysql如何连接表B并使用B的索引作为条件

时间:2013-10-13 09:53:19

标签: mysql join indexing conditional-statements

SQL1:

SELECT
  p.*
FROM `post` p
  JOIN `user` u
    ON p.uid = u.uid
WHERE u.apply = 1
    AND u.gender = 1
    AND u.user_type = 1
    AND u.user_target = 2
    AND p.ctime > 1372478164147
ORDER BY p.ctime DESC
LIMIT 100,20;

TABLE用户有一个索引:

idx_uid
idx_apply_gender_user_type_user_target(apply, gender, user_type, user_target)

TABLE post上有一个索引:

idx_ctime

根据mysql doc:http://dev.mysql.com/doc/refman/5.1/en/nested-loop-joins.html

sql将按以下方式执行

loop post for p.ctime > 1372478164147
    step1: fetch user detail with uid(use index idx_uid)
    step2: compare user's detail with where condtion clause
next

我认为这一点是step1将从磁盘缓慢读取(可能存在于缓冲区中).right?

那么如何使用索引 idx_apply_gender_user_type_user_target 或任何其他解决方案?

更新

    +----+-------------+-------+--------+--------------------------------------------------------+----------+------------------+-------+-------------+
| id | select_type | table | type   | possible_keys                                          | key      | key_len | ref              | rows  | Extra       |
+----+-------------+-------+--------+--------------------------------------------------------+-----------+------------------+-------+-------------+
|  1 | SIMPLE      | p     | range  | idx_ctime,idx_uid                                      | idx_ctime| 8       | NULL             | 15301 | Using where |
|  1 | SIMPLE      | u     | eq_ref | PRIMARY,idx_uid,idx_apply_gender_user_type_user_target | PRIMARY  | 15      | p.uid |     1 | Using where |
+----+-------------+-------+--------+--------------------------------------------------------+----------+------------------+-------+-------------+

0 个答案:

没有答案