代码之家  ›  专栏  ›  技术社区  ›  Ram

使用distinct运算符复制

  •  0
  • Ram  · 技术社区  · 7 年前

    我有以下表格。

    create table html_details(A int,b int,c int,d nvarchar(4))
    
    create table pdf_details(A int,b int,c int,d nvarchar(4))
    
    insert into pdf_details values(1,2,3,'pdf')
    insert into pdf_details values(1,2,3,'pdf')
    insert into pdf_details values(4,5,6,'pdf')
    
    insert into html_details values(1,2,3,'html')
    insert into html_details values(1,2,3,'html')
    insert into html_details values(4,5,6,'html')
    

    现在我使用下面的查询来避免每个表中的重复。

    select distinct a,b,c,d from html_details
    union all
    select distinct a,b,c,d from pdf_details
    

    但是上面的查询性能很差,因为两个查询中的函数不同。所以我在外部查询中使用distinct。现在性能有所提高,但它会给出相同的输出吗?两个查询在逻辑上是相同的吗?

    select distinct a,b,c,d from (
    select  a,b,c,d from html_details
    union all
    select a,b,c,d from pdf_details
    )a
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Raman Shrivastava    7 年前

    否。它不会返回相同的输出。

    Distinct in individual查询将从两个查询中获得唯一的记录,然后它将被联合。因此,如果两个查询结果中都有相似的行,那么它们都将出现在最终结果中。

    假设您的数据是:

    表1:

    1,2,3,pdf 1,2,3,pdf 1,2,3,hello

    1,2,3,html 1,2,3,html 1,2,3,hello

    第一种方法的结果将是(最终响应中没有明显的差异)-

    1,2,3,pdf 1,2,3,hello 1,2,3,html 1,2,3,hello

    1,2,3,pdf 1,2,3,html 1,2,3,hello

    我希望这能解释。