我的查询花费了太多时间来获取数据。每个表(ap1,ap2,ap4)有1626条记录。请帮我优化查询
SELECT *
FROM ap1 w1,
ap2 w2,
ap4 w4
WHERE w4.first_name = '2'
AND w4.id = '303'
AND w4.reference like '%AXS%'
AND w1.first_name = w4.first_name
AND w2.first_name = w1.first_name
AND w1.id = w4.id
AND w2.id = w4.id
AND w1.number = w4.number
AND w2.number = w4.number;
由于
答案 0 :(得分:1)
编写查询的正确方法是:
SELECT *
FROM ap1 w1 JOIN
ap2 w2
ON w2.first_name = w1.first_name AND
w2.id = w4.id JOIN
ap4 w4
ON w1.first_name = w4.first_name AND
w1.id = w4.id AND
w1.number = w4.number
WHERE w4.first_name = '2' AND
w4.id = '303' AND
w4.reference like '%AXS%';
这清楚地表明您需要w4(id, first_name, reference, id, number)
上的索引。然后在w1(id, first_name, number)
和w2(id,first_name)`。
但是,这假定连接条件是正确的。如果查询在少量行上表现不佳,那么它们可能是错误的。我建议你一次建立一个表的查询,以确保逻辑是正确的。