关于我应该把索引放在什么cols的MySql?

时间:2013-03-11 15:11:19

标签: mysql sql explain

我有这个问题:

SELECT Concat(f.name, ' ', f.parent_names) AS FullName, 
       stts.name                           AS 'Status', 
       u.name                              AS Unit, 
       city.name                           AS City, 
       (SELECT Group_concat(c.mobile1) 
        FROM   contacts c 
        WHERE  c.id = f.husband_id 
                OR c.id = f.wife_id)       AS MobilePhones, 
       f.phone                             AS HomePhone, 
       f.contact_initiation_date           AS InitDate, 
       f.status_change_date                AS StatusChangeDate, 
       cmt.created_at                      AS CommentDate, 
       cmt.comment                         AS LastComment, 
       f.reconnection_date                 AS ReconnectionDate, 
       (SELECT Group_concat(t.name, ' ') 
        FROM   taggings tgs 
               JOIN tags t 
                 ON tgs.tag_id = t.id 
        WHERE  tgs.taggable_type = 'family' 
               AND tgs.taggable_id = f.id) AS HandlingStatus 
FROM   families f 
       JOIN categories stts 
         ON f.family_status_cat_id = stts.id 
       JOIN units u 
         ON f.unit_id = u.id 
       JOIN categories city 
         ON f.main_city_cat_id = city.id 
       LEFT JOIN comments cmt 
              ON f.last_comment_id = cmt.id 
WHERE  1 = 0 
        OR ( u.is_busy = 1 ) 
        OR ( f.family_status_cat_id = 1423 ) 
        OR ( f.family_status_cat_id = 1422 
             AND f.status_change_date BETWEEN '2011-03-21' AND '2012-03-13' ) 

我的问题很具体。关于这条线:

 SELECT GROUP_CONCAT( c.mobile1 ) 
    FROM contacts c
    WHERE c.id = f.husband_id
    OR c.id = f.wife_id
    ) AS MobilePhones

当我使用EXPLAIN时,似乎这个查询很糟糕。我得到这个表(c =联系人):38307行。 我应该根据查询将索引放在哪些列上? 我尝试了mobile1 - 但没有改进(BTW - family_id在contacts表中被编入索引)。

我附上解释结果的图像: EXPLAIN

也许有人可以帮我优化查询...

3 个答案:

答案 0 :(得分:0)

您要搜索的任何列,以加快此过程。请记住,密钥已经编入索引。

答案 1 :(得分:0)

好吧,似乎使用GROUP_CONCAT就是问题所在。 我只是把妻子和丈夫的手机分成2个不同的栏目。 首先,我认为使用GROUP_CONCAT会更快,但事实证明它非常错误。

答案 2 :(得分:0)

出于好奇,查询的表现是什么

SELECT GROUP_CONCAT( c.mobile1 ) 
    FROM contacts c
    WHERE c.id IN(f.husband_id, f.wife_id)
    ) AS MobilePhones