如何应用索引此查询的索引

时间:2017-05-25 05:40:10

标签: php mysql indexing

SELECT  user_id,username,full_name,display_name,profile_pic,email,
        fb_id,image1,image2,image3,image4,image5,default_pic,
        street_address,locality,country,state,is_verified,is_online,
        city,image6,image7,image8,image9,image10,last_login,
        IFNULL( (
                SELECT  STATUS
                    FROM  vidioo_contacts
                    WHERE  (contact_id = '55000'
                              AND  user_id = vu.user_id
                          )
                      OR  (contact_id = vu.user_id
                              AND  user_id = '55000')),0) AS STATUS,
        (3959 * ACOS( COS(RADIANS(0)) * COS(RADIANS(latitude)) * 
           COS(RADIANS(longitude) - RADIANS(0)) + SIN(RADIANS(0)) *
           SIN(RADIANS(latitude)))
           ) AS distance
    FROM  vidioo_users vu
    WHERE  user_id != '55000'
      AND  gender LIKE 
        ( SELECT  CASE WHEN show_me = 'everyone'
                     THEN '%'
                     ELSE IF(LENGTH(show_me) < 1, '%', show_me)
                  END
            FROM  vidioo_users
            WHERE  user_id = '55000'
            LIMIT  1 
        )
      AND  IFNULL(vu.is_deleted,0) != 55000
      AND  vu.user_id NOT IN (
        SELECT  DISTINCT contact_id
            FROM  vidioo_blocked_users
            WHERE  bloked_by_user = 55000
                          )
      AND  DATEDIFF(NOW(),last_login) < 7
    ORDER BY  last_login DESC
    LIMIT  0,20

我希望将索引应用于此查询。

3 个答案:

答案 0 :(得分:1)

如果表有多列索引,则mysql使用索引的最左前缀。例如,您有以下选择查询 -

`SELECT * FROM tbl_name WHERE col1 = val1; SELECT * FROM tbl_name WHERE col1 = val1 AND col2 = val2;

SELECT * FROM tbl_name WHERE col2 = val2; SELECT * FROM tbl_name WHERE col2 = val2 AND col3 = val3;`

如果(col1,col2,col3)上存在索引,则只有前两个查询使用索引。第三个和第四个查询确实涉及索引列,但(col2)和(col2,col3)不是(col1,col2,col3)的最左前缀。

在您的情况下,您必须创建3个索引

  1. Index_1(user_id,gender,last_login)
  2. Index_2(USER_ID)
  3. Index_3(bloked_by_user)
  4. 注意: - 索引太多会降低INSERT查询处理速度。 有关详细信息Click here

答案 1 :(得分:0)

尝试在这四个表列上添加索引,它应该有所帮助:

contact_id,
user_id,
is_deleted,
last_login.

答案 2 :(得分:0)

除了其他建议外,请将AND DATEDIFF(NOW(),last_login) < 7更改为

last_login > NOW() - INTERVAL 7 DAY

您在函数(last_login)中隐藏了列DATEDIFF,使其无法使用索引编制。然后,还要添加

INDEX(last_login)

(可能没有帮助,但也可能。)

另外,更改

AND  vu.user_id NOT IN (
    SELECT  DISTINCT contact_id
        FROM  vidioo_blocked_users
        WHERE  bloked_by_user = 55000
                      )

AND NOT EXISTS( SELECT * FROM vidioo_blocked_users
        WHERE  bloked_by_user = 55000
          AND  contact_id = vu.user_id )

一起
INDEX(bloked_by_user, contact_id) -- in either order