我正在执行两个查询。一个返回记录数和一个获取结果的记录。但是我只想要记录总数的查询,它比获取结果的查询需要相同的时间。为什么?这是我的SQL。我正在使用SQL 2014:
(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)
group by title, version
EXCEPT
SELECT DISTINCT title, version
FROM book AS b
WHERE b.title IS NOT NULL AND EXISTS (SELECT * FROM user AS u WHERE u.column2 = b.column1)
group by title, version
) c )
答案 0 :(得分:0)
试试这个:
(SELECT count(*) as id
FROM (
SELECT DISTINCT title, version
FROM book b left join user u on b.column1=u.column1
WHERE b.title IS NOT NULL and u.column1 is null
EXCEPT
SELECT DISTINCT title, version
FROM book b join user u on b.column1=u.column2
WHERE b.title IS NOT NULL
) c )
答案 1 :(得分:0)
group by
和select distinct
(except
无论如何都这样做):
SELECT count(*) as id
FROM (SELECT title, version
FROM book b
WHERE b.title IS NOT NULL AND NOT EXISTS (SELECT 1 FROM user u WHERE u.column1 = b.column1)
EXCEPT
SELECT title, version
FROM book b
WHERE b.title IS NOT NULL AND EXISTS (SELECT 1 FROM user u WHERE u.column2 = b.column1)
) c;
下一步:确保您在user(column2)
和user(column1)
上有索引。
有关数据的更多信息,可能会提出进一步的建议。