什么是编写查询的优化方法

时间:2017-11-20 12:31:43

标签: mysql

我有以下查询,我想优化

SELECT  -- COUNT(message_queue_id_pk)
message_queue_id_pk, q.media_filename_original, a.media_filename_original, 
processed_flag , schedule_flag, q.message_mode, q.added_datetime
FROM messages_queue q
LEFT JOIN messages_all a ON q.media_filename_original = 
a.media_filename_original
WHERE q.message_type_flag != 1 AND a.media_filename_original IS NULL AND 
processed_flag = 2
LIMIT 10;

1 个答案:

答案 0 :(得分:0)

你不应该在where where条件中使用与左连接表相关的列..这样你就有了一个内连接所以.. 首先构建正确的查询,在ON条件中移动a.media_filename_original IS NULL

假设processed_flag和schedule_flag在q表中

  SELECT  -- COUNT(message_queue_id_pk)
    message_queue_id_pk
    , q.media_filename_original
    , a.media_filename_original
    , processed_flag 
    , schedule_flag
    , q.message_mode
    , q.added_datetime
  FROM messages_queue q
  LEFT JOIN messages_all a ON q.media_filename_original = a.media_filename_original 
            AND a.media_filename_original IS NULL
  WHERE q.message_type_flag != 1 
  processed_flag = 2
  LIMIT 10;