选择计数需要太长时间才能执行

时间:2018-05-24 19:07:39

标签: sql count

我正在执行两个查询。一个返回记录数,一个显示结果。但是,如果显示结果的查询执行时间不到1秒,那么返回记录总数的查询需要11秒才能完成?它应该是相反的,不是吗?

返回记录总数的SQL将在11秒后执行

(SELECT count(*) as id
      FROM (
      SELECT DISTINCT title, version
      FROM book AS b
      WHERE b.title IS NOT NULL AND NOT EXISTS (SELECT * FROM user AS u WHERE u.column1 = b.column1)
      UNION ALL
      SELECT DISTINCT title, version
      FROM book2 AS b2
      WHERE b.title IS NOT NULL AND EXISTS (SELECT * FROM user AS u WHERE u.column2 = b.column1)
    ) c ) 

显示结果的SQL在不到1秒的时间内执行

   SELECT DISTINCT title, version
   FROM book AS b
   WHERE b.title IS NOT NULL AND NOT EXISTS (SELECT * FROM user AS u WHERE u.column1 = b.column1)
   UNION ALL
   SELECT DISTINCT title, version
   FROM book2 AS b2
   WHERE b.title IS NOT NULL AND EXISTS (SELECT * FROM user AS u WHERE u.column2 = b.column1)

4 个答案:

答案 0 :(得分:0)

您正在比较苹果和橘子。 count(*)版本必须先处理所有数据,然后才能返回任何内容。

更详细的版本可以在行变为可用时开始返回行 - 这可能是在第一个子查询开始返回行时。

我不认为这些查询中的任何一个都是您真正需要的,但这个问题并没有提供这些信息。

此外,bookversion 不是是唯一的吗?我想知道这是否符合您的要求:

  SELECT COUNT(*)
  FROM book b
  WHERE b.title IS NOT NULL AND
        ( NOT EXISTS (SELECT 1 FROM user u WHERE u.column1 = b.column1) OR
          EXISTS (SELECT 1 FROM user u WHERE u.column2 = b.column1)
        );

您还可以使用COUNT(DISTINCT)

SELECT COUNT(DISTINCT b.title + ':' + b.version)
. . .

答案 1 :(得分:0)

你可以试试这个:

SELECT COUNT(1)
FROM
(
SELECT DISTINCT title, version
FROM book b
LEFT JOIN u ON b.column1 = u.column2
LEFT JOIN u2 ON b.column1 = u2.column1
WHERE u2.column1 IS NULL
AND b.title IS NOT NULL
) sub

答案 2 :(得分:0)

您可以在此处改进查询,这是其中一个示例,您可以查看其他朋友分享的信息

SELECT COUNT(1)
FROM book AS b
LEFT OUTER JOIN User U ON u.Column1 = b.column1
LEFT OUTER JOIN user u1 ON u1.Column2 = b.column1
WHERE b.title IS NOT NULL 
AND u.Id IS NULL -- with assumption u might have another column id
AND u1.Id IS NULL -- with assumption u1 might have aother column or
GROUP BY title,Version

答案 3 :(得分:0)

(SELECT **count(title)** as id
      FROM (
      SELECT DISTINCT title, version
      FROM book AS b
      WHERE b.title IS NOT NULL AND NOT EXISTS (SELECT * FROM user AS u WHERE u.column1 = b.column1)
      UNION ALL
      SELECT DISTINCT title, version
      FROM book2 AS b2
      WHERE b.title IS NOT NULL AND EXISTS (SELECT * FROM user AS u WHERE u.column2 = b.column1)
    ) c ) 

" *"永远不可取,因为它也解释了所有不必要的细节。