【发布时间】:2016-02-13 23:30:04
【问题描述】:
考虑以下查询:
SELECT
nodos.nombre,
(SELECT super FROM atributo_16 WHERE nodoid=nodos.nodoid ORDER BY fecha DESC,created_at LIMIT 1) AS descuento_navision_super_cif,
(SELECT regular FROM atributo_16 WHERE nodoid=nodos.nodoid ORDER BY fecha DESC,created_at LIMIT 1) AS descuento_navision_regular_cif,
(SELECT diesel FROM atributo_16 WHERE nodoid=nodos.nodoid ORDER BY fecha DESC,created_at LIMIT 1) AS descuento_navision_diesel_cif
FROM
nodos
WHERE
nodos.nodotipoid=8;
这很好用,但速度很慢。在此示例中,查询重复 (3x) 到同一个表并使用相同的 WHERE。真正的查询对不同的表有 20 个这样的子查询。我想优化查询。
这是我使用派生表加快速度的尝试之一。制作一个 [fecha, created_at] 索引,这提高了速度,但查询不起作用,因为查询的 LIMIT 1 部分在 JOIN 之前应用,我似乎无法添加 nodoid WHERE 语句的一部分,这将解决问题。
SELECT
nodos.nombre,
descuentos.super AS descuento_navision_super_cif,
descuentos.regular AS descuento_navision_regular_cif,
descuentos.diesel AS descuento_navision_diesel_cif
FROM
nodos
LEFT JOIN (SELECT nodoid, super, regular, diesel, ulsd
FROM atributo_16 ORDER BY fecha DESC,
created_at LIMIT 1)descuentos ON descuentos.nodoid=nodos.nodoid
WHERE
nodos.nodotipoid=8
更新 这是第一个查询的 EXPLAIN 表。
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY nodos ref nodotipoid nodotipoid 4 const 226
4 DEPENDENT SUBQUERY atributo_16 ref nodoid nodoid 4 nodos.nodoid 376 Using where; Using filesort
3 DEPENDENT SUBQUERY atributo_16 ref nodoid nodoid 4 nodos.nodoid 376 Using where; Using filesort
2 DEPENDENT SUBQUERY atributo_16 ref nodoid nodoid 4 nodos.nodoid 376 Using where; Using filesort
【问题讨论】:
-
您能否发布
EXPLAIN SELECT以及有关该表的一些统计信息,例如每个表中的索引和行数。 -
nodos 的行数约为 400,attributo_16 的行数约为 10000
-
不确定我是否遗漏了什么——但你为什么在第二个查询中使用子选择。据我所知,只需在 nodeid 上加入两个表,然后使用 ORDER BY 和 LIMIT 1 就可以了。
-
一个简单的连接会为每个 nodeid 返回 1000 行。我只需要那张桌子上最新的寄存器。
-
我们可以看看 Giorgios 查询的解释吗
标签: mysql subquery limit derived