LEFT OUTER JOIN的SQL查询替代/优化

时间:2010-09-04 16:35:02

标签: optimization sqlite left-join

我有以下查询:

SELECT
    `pokemon_moves`.`pokemon_move_method_id`,
    `pokemon_moves`.`level`,
    `move`.`id`,
    `move`.`name`
FROM
    `pokemon_moves`
LEFT OUTER JOIN
    `moves` `move` ON
        `move`.`id` = `pokemon_moves`.`move_id`
WHERE
    `pokemon_moves`.`pokemon_move_method_id` < '4' AND
    `pokemon_moves`.`pokemon_id` = '2' AND
    `pokemon_moves`.`version_group_id` = '6'
ORDER BY
    CAST(`pokemon_moves`.`level` as INTEGER) ASC,
    `move`.`name` ASC

它有点慢,我认为这是因为pokemon_moves表中的每一行都查询moves表,而不是仅查询符合WHERE子句的那一行。写这个查询会有什么更好的选择?

请注意,此(外部)表中的整数存储为文本

1 个答案:

答案 0 :(得分:1)

尝试使用INNER JOIN,并将WHERE条件放入JOIN语句中。例如:

SELECT
    `pokemon_moves`.`pokemon_move_method_id`,
    `pokemon_moves`.`level`,
    `move`.`id`,
    `move`.`name`
FROM
    `pokemon_moves`
INNER JOIN
    `moves` `move` ON
    `pokemon_moves`.`pokemon_id` = '2' AND
    `pokemon_moves`.`version_group_id` = '6' AND
    `pokemon_moves`.`pokemon_move_method_id` < '4' AND
    `move`.`id` = `pokemon_moves`.`move_id`
ORDER BY
    CAST(`pokemon_moves`.`level` as INTEGER) ASC,
    `move`.`name` ASC