考慮以下查詢的最新值:MySQL的 - 最有效的方式來獲得一個連接表
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,atributo_16的行數是〜10000 – JoeGalind
不確定我是否錯過了某些內容 - 但爲什麼在第二個查詢中使用子查詢。據我所知,你只要加入nodeid上的兩個表,然後使用ORDER BY和LIMIT 1即可。 –