0

我一直在解决这个问题,听到新的想法应该很高兴:)

我有一张像这样的数十亿条记录的表

TAB_IX (int) (PK)
TAB_ID (int) (PK)
PR_ID (int) (PK)
SP_ID (int) (PK)(IX)
....

以前我正在检索这样的数据

SELECT TAB_ID, COUNT (SP_ID) as HITS FROM table t
INNER JOIN table_sp s on t.SP_ID = s.ID
WHERE TAB_IX = @tab_inx 
AND PR_ID IN (SELECT PR_ID FROM @pr_id)
AND s.NAME IN (SELECT DISTINCT NAME FROM @sp_names)  
GROUP BY TAB_ID

table_sp 是一个有 10k 条记录的小表(ID (int) (PK), NAME (varchar) (IX))

@pr_id 和 @sp_names 是一列的表变量

查询非常快(大约 2-3 秒);现在我不想区分具有不同 PR_ID 和相同 TAB_IX、TAB_ID、SP_ID 的记录

所以例如像这样的记录

TAB_IX - TAB_ID - PR_ID - SP_ID
1      - 700    - 1     - 100
1      - 700    - 2     - 100

应视为一。

唯一的方法似乎是做一个额外的 GROUP BY

像这样

SELECT TAB_ID, COUNT(SP_ID) as HITS FROM (
SELECT TAB_ID, SP_ID, COUNT (PR_ID) FROM table 
WHERE TAB_IX = @tab_inx 
AND PR_ID in (select PR_ID from @pr_id)
AND s.NAME IN (SELECT DISTINCT NAME FROM @sp_names)
GROUP BY TAB_ID, SP_ID) AS DUMMY
GROUP BY TAB_ID

问题在于性能,因为添加这个额外的 GROUP BY 操作看起来很痛苦。

您对改进查询有什么想法吗?

提前致谢 :)

4

1 回答 1

1

我想在原始查询中指定要计数DISTINCT SP_ID的就可以了

SELECT TAB_ID, COUNT (DISTINCT SP_ID) as HITS FROM table t
INNER JOIN table_sp s on t.SP_ID = s.ID
WHERE TAB_IX = @tab_inx 
AND PR_ID IN (SELECT PR_ID FROM @pr_id)
AND s.NAME IN (SELECT DISTINCT NAME FROM @sp_names)  
GROUP BY TAB_ID
于 2013-02-20T09:45:04.857 回答