【问题标题】:How to write a more optimized and simple query - Parent Child Relation?如何编写更优化、更简单的查询——父子关系?
【发布时间】:2017-07-12 20:57:08
【问题描述】:

我有一个具有关系的医疗数据表(类似于父母和孩子)。 为了简单起见,我考虑了一个具有实际父子关系的表。 下表是:

表名:关系

Parent | Child
------ | ------
Mike   |John
Aliss  |John
John   |Chris
Brad   |David
Kate   |Brad
Alexa  |Shawn
Matt   |Thoa 

我已经编写了获取 GrandParent、Parent 和 Grandchild 关系的查询。

SELECT t1.grandchild, 
       t2.grandparent,
       t1.parent,
       t2.child
FROM   (SELECT child AS Grandchild, 
               parent 
        FROM   relations 
        WHERE  parent IN (SELECT DISTINCT( r.parent ) 
                          FROM   relations r 
                                 JOIN relations t 
                                   ON r.parent = t.child)) AS t1 
       INNER JOIN (SELECT parent AS Grandparent, 
                          child 
                   FROM   relations 
                   WHERE  child IN (SELECT DISTINCT( r.parent ) 
                                     FROM   relations r 
                                            JOIN relations t 
                                              ON r.parent = t.child)) AS t2 
               ON t1.parent = t2.child 
ORDER  BY t1.grandchild; 

这是关键,现在实际数据有 30015924 行,当我使用上述查询运行报告时,需要很长时间才能获取数据。

我看到了执行计划,并且有许多“嵌套循环”和惰性线轴。 我正在尝试编写一个更高效的查询,该查询在大型数据集上执行速度更快。

联合为不同的关系工作。 这是我编写的最有效的查询还是有更好的版本?

谢谢。

【问题讨论】:

  • DISTINCT 关键字会使其运行缓慢。如果不需要,您可以将其取出。表格是否也被索引了?
  • 表上没有索引,因为它非常频繁地更新和插入。
  • 您使用的是什么版本的 sql server?你有什么索引?
  • 这个样本数据的期望结果是什么?
  • 我得到了想要的结果,只是执行速度很慢

标签: sql sql-server sqlperformance


【解决方案1】:

这是一个更简单(并且可能在性能方面更好)的查询,以获得完全相同的结果:

首先,创建并填充示例数据(在您以后的问题中保存我们这一步):

CREATE TABLE relations
(
    Parent varchar(10),
    Child varchar(10)
)

INSERT INTO relations VALUES

('Mike', 'John'),
('Aliss', 'John'),
('John', 'Chris'),
('Brad', 'David'),
('Kate', 'Brad'),
('Alexa', 'Shawn'),
('Matt', 'Thoa')

查询:

SELECT  sg.child as grandchild,
        fg.Parent as grandparent,
        fg.child as parent,
        sg.Parent as parent
FROM relations as fg -- stands for first generation
INNER JOIN
(
    SELECT parent, child
    FROM relations
) as sg ON fg.child = sg.parent -- second generation

结果:

grandchild  grandparent parent  parent
Chris       Mike        John    John
Chris       Aliss       John    John
David       Kate        Brad    Brad

See a live demo on rextester(我也将您的查询粘贴到那里以比较结果。)

【讨论】:

  • 谢谢...下次一定会放入create语句
  • 查询呢?有帮助吗?
  • 是的,查询运行速度比我的快得多。我还在表上创建了索引,我猜这有助于提高性能。
【解决方案2】:

我经常发现,与使用嵌套、派生查询相比,使用联合大大加快了查询时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    相关资源
    最近更新 更多