查询JSON对象时MySQL查询超时

时间:2019-04-28 17:48:44

标签: mysql json query-optimization

以下查询似乎会生成一个无限循环,因为它在30秒后超时。在C ++中运行它永远不会返回代码。

SELECT author_obj->>'$.name' FROM author WHERE author_obj->'$.name' NOT IN 
    (SELECT DISTINCT author_obj->'$.name' 
    FROM response INNER JOIN author ON response.author_id = author.id 
    WHERE response.parent IS NOT NULL
    GROUP BY author.id);

内部运行正常,并在1.5秒内返回数据库中已回答其他帖子的作者。

查询的目标是找到所有只发布消息但从不回答其他用户的用户,这些用户被保存为JSON对象。

1 个答案:

答案 0 :(得分:0)

SELECT author_obj->>'$.name'
FROM author 
WHERE author_obj->'$.name' NOT IN 
    (SELECT DISTINCT author_obj->'$.name' 
    FROM response
    INNER JOIN author ON response.author_id = author.id 
    WHERE response.parent IS NOT NULL
    GROUP BY author.id)

可能可以更快:

SELECT a1.author_obj->>'$.name'
FROM author a1
WHERE NOT EXISTS
    (SELECT 1 FROM
    FROM response r
    INNER JOIN author a2 ON r.author_id = a2.id 
    WHERE a2.author_obj->'$.name' = a1.author_obj->'$.name'
      AND r.parent IS NOT NULL)

(注意:我可能没有正确重构它。)