Mysql视图很慢

时间:2016-12-11 09:47:48

标签: mysql join

我的mysql视图在成千上万的数据中真的很慢,我们如何才能改进这个功能?

在10000s数据中获取此视图时,则需要超过30秒。我们怎么能修改这个视图表?

SELECT 
    i.jo_in_id,
    j.*,
    i.jo_in_week_number,
    i.jo_in_client_ref_no,
    i.cl_id AS jo_in_cl_id,
    c.cl_short_name,
    c.cl_business_name,
    m.me_first_name,
    m.me_last_name, 
    m.me_mobile,
    sk.sk_name,
    sk.sk_ticketed,
    ti.ti_id,
    ta.ta_name,
    u.un_id,
    u.un_from,
    u.un_to,
    v.ve_name,
    mp.vmp_name,
    r.vr_name 
FROM 
    jo_2_no j2n,
    jo_in_numbers i,
    jobs j
LEFT JOIN venues_new v ON j.ve_id = v.ve_id
LEFT JOIN venues_meeting_place mp ON j.vmp_id = mp.vmp_id
LEFT JOIN venues_rooms r ON j.vr_id = r.vr_id
LEFT JOIN clients c ON j.cl_id = c.cl_id
LEFT JOIN members m ON j.me_id = m.me_id
LEFT JOIN skills sk ON j.sk_id = sk.sk_id
LEFT JOIN tasks ta ON j.ta_id = ta.ta_id
LEFT JOIN crew_tickets ti ON j.sk_id = ti.sk_id AND j.me_id = ti.me_id AND j.jo_time_off < ti.ti_expire
LEFT JOIN unavailability u ON j.me_id = u.me_id AND ((j.jo_time_on BETWEEN u.un_from AND u.un_to) OR  (j.jo_time_on BETWEEN u.un_from AND u.un_to))
WHERE 
    j.jo_id = j2n.jo_id
    AND j2n.jo_in_numbers_id = i.jo_in_id

用户EXPLAIN SELECT后面是输出

enter image description here

1 个答案:

答案 0 :(得分:0)

在您的EXPLAIN中,我看到您使用表扫描(类型:ALL )读取已加入的表格tiu。这可能是您表现最大的问题。

您应确保已创建以下索引:

ALTER TABLE crew_tickets ADD KEY (sk_id, me_id, ti_expire);

ALTER TABLE unavailability ADD KEY (me_id, un_from, un_to);

这应该有助于这些表的连接使用索引查找而不是表扫描。我认为它们也可以作为覆盖索引来访问。

另外,请不要使用过时的“逗号连接”。特别是不要混合两种风格。当您对逗号连接和JOIN运算符之间的优先顺序感到惊讶时,它会咬你。请参阅Can someone help explain why not using a SQL JOIN is bad practice and wrong?Error on JOIN mysql中的示例。

以这种方式编写联接:

FROM jo_2_no j2n 
INNER JOIN jo_in_numbers i ON j2n.jo_in_numbers_id = i.jo_in_id
INNER JOIN jobs j ON j.jo_id = j2n.jo_id
LEFT JOIN venues_new v ON j.ve_id = v.ve_id
LEFT JOIN venues_meeting_place mp ON j.vmp_id = mp.vmp_id
LEFT JOIN venues_rooms r ON j.vr_id = r.vr_id
LEFT JOIN clients c ON j.cl_id = c.cl_id
LEFT JOIN members m ON j.me_id = m.me_id
LEFT JOIN skills sk ON j.sk_id = sk.sk_id
LEFT JOIN tasks ta ON j.ta_id = ta.ta_id
LEFT JOIN crew_tickets ti ON j.sk_id = ti.sk_id 
  AND j.me_id = ti.me_id AND j.jo_time_off < ti.ti_expire
LEFT JOIN unavailability u ON j.me_id = u.me_id 
  AND j.jo_time_on BETWEEN u.un_from AND u.un_to

我删除了u的加入条件中的冗余术语。优化器可能会消除这种逻辑,但为什么要让它如此努力呢?