0

我在 MySQL 数据库中有两个表。一个表包含默认值,另一个表包含覆盖值和添加。我编写了两个单独的工作 SQL 语句来从两者中选择所有元素,然后当有覆盖时,替换默认表的值。

SELECT
    d.id AS did, IFNULL(i.id, d.id) AS id, d.parent_id AS parent_id,
    IFNULL(i.content, d.content) AS content, d.order_id AS ord
  FROM cci d 
    LEFT JOIN instructions i ON d.order_id = i.order_id
      AND i.parent_id = d.parent_id
      AND i.specification_id = 'SOME ID'
  WHERE d.parent_id = 'SOME PARENT' AND d.specification_id = '1'
UNION ALL SELECT
    i.id AS did, i.id AS id, i.parent_id AS parent_id,
    i.content AS content, i.order_id AS ord
  FROM instructions i
  WHERE i.parent_id = 'SOME PARENT' 
    AND i.specification_id = 'SOME ID' 
    AND NOT EXISTS (SELECT 1 FROM cci d WHERE d.order_id = i.order_id AND d.parent_id = i.parent_id)

这两部分单独工作正常且符合预期,但是当我将它们放在一起时,MySQL 会飙升到 90% 的 CPU 并冻结。显然有些事情不太正常。什么会导致这种冻结,或者我的陈述有什么问题?

谢谢

编辑:

解释的输出是:

id  | select_type          | table      | type | possible_keys | key  | key_len | ref  | rows | Extra
————————————————————————————————————————————————————————————————————————————————————————————————————————
1   | PRIMARY              | d          | ALL  | NULL          | NULL | NULL    | NULL | 105  | Using where
1   | PRIMARY              | i          | ALL  | NULL          | NULL | NULL    | NULL | 4    |  
2   | UNION                | i          | ALL  | NULL          | NULL | NULL    | NULL | 4    | Using where
3   | DEPENDENT SUBQUERY   | d          | ALL  | NULL          | NULL | NULL    | NULL | 105  | Using where
NULL| UNION RESULT         | <union1,2> | ALL  | NULL          | NULL | NULL    | NULL | NULL |  
4

1 回答 1

0

问题在于优化器,它正在切换到非最佳连接策略。

问题可能是与 UNION ALL 一起出现的“不在”。

我认为您可以重写查询。这是一个开始:

SELECT (case when d.specification_id = '1' then d.id else i.id) AS did,
       ...
FROM cci d LEFT JOIN
     instructions i
     ON d.order_id = i.order_id  AND
        i.parent_id = d.parent_id AND
        i.specification_id = 'SOME ID' left outer join
     cci parent
     on d.parent_id = parent.parent_id
WHERE d.parent_id = 'SOME PARENT' AND d.specification_id in ('1', 'SOME ID')

或者,使用临时表也可以解决您的问题。

于 2012-05-10T15:15:41.973 回答