mysql - 如何使用许多 JOIN 提高查询性能

标签 mysql sql performance select query-optimization

我有一个查询(目的是制作 View ),它使用一些连接来获取每一列。对于添加的每组联接,性能会迅速(呈指数级下降?)。

加快查询速度的好方法是什么?请查看查询中的评论。

如果有帮助,这就是使用 WordPress 数据库架构。

这是 EXPLAIN 的截图 enter image description here

产品表

+--+----+
|id|name|
+--+----+
|1 |test|
+--+----+

元数据表

+----------+--------+-----+
|product_id|meta_key|value|
+----------+--------+-----+
|1         |price   |9.99 |
+----------+--------+-----+
|1         |sku     |ABC  |
+----------+--------+-----+

TERM_RELATIONSHIPS 表

+---------+----------------+
|object_id|term_taxonomy_id|
+---------+----------------+
|1        |1               |
+---------+----------------+
|1        |2               |
+---------+----------------+

TERM_TAXONOMY 表

+----------------+-------+--------+
|term_taxonomy_id|term_id|taxonomy|
+----------------+-------+--------+
|1               |1      |size    |
+----------------+-------+--------+
|2               |2      |stock   |
+----------------+-------+--------+

条款表

+-------+-----+
|term_id|name |
+-------+-----+
|1      |500mg|
+-------+-----+
|2      |10   |
+-------+-----+

查询

SELECT 
  products.id,
  products.name,
  price.value AS price,
  sku.value AS sku,
  size.name AS size
FROM products

/* These joins are performing quickly */

INNER JOIN `metadata` AS price ON products.id = price.product_id AND price.meta_key = 'price'
INNER JOIN `metadata` AS sku ON products.id = sku.product_id AND sku.meta_key = 'sku'

/* Here's the part that is really slowing it down - I run this chunk about 5 times with different strings to match */

INNER JOIN `term_relationships` AS tr ON products.id = tr.object_id
  INNER JOIN `term_taxonomy` AS tt
  ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = 'size'
    INNER JOIN `terms` AS size
    ON tt.term_id = size.term_id

最佳答案

您的性能问题很可能是由与“term_taxonomy”表的连接引起的。
所有其他联接似乎都使用主键(您可能在其中有工作索引)。

所以我的建议是在 term_taxonomy_idterm_id 上添加复合索引(或者如果必须:taxonomy) .像这样:

CREATE UNIQUE INDEX idx_term_taxonomy_id_taxonomy
ON term_taxonomy( term_taxonomy_id, taxonomy);

希望这会对你有所帮助。

关于mysql - 如何使用许多 JOIN 提高查询性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20910369/

相关文章:

javascript - 当用户收到新消息时重新加载页面不起作用

php - 计算表中的行位置

c# - Directory.GetFiles() 性能问题

mySQL PDO 未在 phpinfo() 中启用

php - 使用 PHP 和 MySQL 创建动态表单

sql - 如何组合来自两个存储过程调用的结果集?

sql - 在 SP 中搜索

php - 使用 native PHP 功能是否比在 PHP 循环中做同样的事情更快?为什么?

performance - 为什么我无法在 32 位和 64 位 JVM 上观察到相同的性能改进?

mysql - Doctrine 查询 Mysql 左连接语法错误