在MySQL中为相关子查询优化索引

时间:2018-07-19 16:20:46

标签: mysql sql indexing

我有一个带有相关子查询的查询,想知道应该为哪个字段建立索引以实现最佳性能?例如,查询(如下所示)显示名称中带有“ smi”的任何人的所有订单。该查询通过订单和客户表中的共享客户编号从客户表中获取客户名称。我对此查询非常困惑,因为它大部分是由php开发工具自动生成的。那么,考虑到这些限制,应该索引哪些字段以获得最佳性能?

SELECT *, (SELECT CONCAT(customers.last, ', ', customers.first)
FROM customers WHERE customers.cust_num = orders.cust_num) AS c_lastname 
FROM orders WHERE (SELECT CONCAT(customers.last, ', ', customers.first) 
FROM customers WHERE customers.cust_num = orders.cust_num) LIKE '%smi%' 
ORDER BY order_id DESC LIMIT 0, 20

EXPLAIN给我:

"1" "PRIMARY"   "orders"    "index" \N  "PRIMARY"   "4" \N  "20"    "Using where"
"3" "DEPENDENT SUBQUERY"    "customers" "eq_ref"    "PRIMARY"   "PRIMARY"   "4" "orders.cust_num"   "1" ""
"2" "DEPENDENT SUBQUERY"    "customers" "eq_ref"    "PRIMARY"   "PRIMARY"   "4" "orders.cust_num"   "1" ""

2 个答案:

答案 0 :(得分:0)

我首先将查询重写为:

SELECT o.*, c.last_name
FROM (SELECT cust_name, CONCAT(c.last, ', ', c.first) as c_lastname
      FROM customers c
      HAVING c_lastname LIKE '%smi%'
     ) c JOIN
     orders o
     ON o.cust_num = c.cust_num
ORDER BY order_id DESC
LIMIT 0, 20;

除非您真的是指like,否则我认为liike 'smi%'上您无能为力。

但是,您可以随后在orders(cust_num)上为join创建一个索引。关于外部order by,您无能为力。

答案 1 :(得分:0)

看起来像这样的查询会更简单:

SELECT o.*, CONCAT(c.`last`, ', ', c.`first`) AS cName
FROM orders AS o
INNER JOIN customers AS c ON o.cust_num = c.cust_num
WHERE c.`last` LIKE '%smi%' OR c.`first` LIKE '%smi%'
ORDER BY order_id DESC 
LIMIT 0, 20

或者,类似于戈登的:

SELECT o.*, c.Name
FROM orders AS o
INNER JOIN (
    SELECT cust_num, CONCAT(`last`, ', ', `first`) AS Name 
    FROM customers
    WHERE `last` LIKE '%smi%' OR `first` LIKE '%smi%'
) AS c ON o.cust_num = c.cust_num
ORDER BY order_id DESC 
LIMIT 0, 20;

第一个避免子查询,但是第二个子查询将减少同一客户订单上的冗余CONCAT操作;效果更好的表可能取决于表中的实际数据。

...并且要呼应戈登,关于“%smi%”您无能为力; MySQL不会从中间索引字符串,因此领先的通配符基本上消除了使用索引的可能性。