是否有更好的方法来执行这样的查询:
SELECT COUNT(*)
FROM (SELECT DISTINCT DocumentId, DocumentSessionId
FROM DocumentOutputItems) AS internalQuery
我需要数一下这个表中不同项的数量,但不同项超过两列。
我的查询工作得很好,但我想知道我是否可以只使用一个查询(不使用子查询)得到最终结果
是否有更好的方法来执行这样的查询:
SELECT COUNT(*)
FROM (SELECT DISTINCT DocumentId, DocumentSessionId
FROM DocumentOutputItems) AS internalQuery
我需要数一下这个表中不同项的数量,但不同项超过两列。
我的查询工作得很好,但我想知道我是否可以只使用一个查询(不使用子查询)得到最终结果
当前回答
我用过这种方法,对我很有效。
SELECT COUNT(DISTINCT DocumentID || DocumentSessionId)
FROM DocumentOutputItems
对于我的案例,它提供了正确的结果。
其他回答
如果您试图提高性能,可以尝试在两个列的散列或连接值上创建持久计算列。
一旦它被持久化,只要列是确定的,并且您使用的是“正常的”数据库设置,就可以对其建立索引和/或在其上创建统计信息。
我相信计算列的不同计数将等效于您的查询。
一些SQL数据库可以使用元组表达式,所以你可以这样做:
SELECT COUNT(DISTINCT (DocumentId, DocumentSessionId))
FROM DocumentOutputItems;
如果你的数据库不支持这个,可以根据@oncel-umut-的建议来模拟CHECKSUM或其他提供良好唯一性的标量函数。 COUNT(DISTINCT CONCAT(documententid, ':', DocumentSessionId)))。
MySQL特别支持COUNT(DISTINCT expr, expr,…),这是非sql标准语法。它还指出,在标准SQL中,您必须在COUNT(DISTINCT…)中对所有表达式进行连接。
元组的一个相关用法是执行IN查询,例如:
SELECT * FROM DocumentOutputItems
WHERE (DocumentId, DocumentSessionId) in (('a', '1'), ('b', '2'));
我有一个类似的问题,但我的查询是一个子查询与比较数据在主查询。喜欢的东西:
Select code, id, title, name
(select count(distinct col1) from mytable where code = a.code and length(title) >0)
from mytable a
group by code, id, title, name
--needs distinct over col2 as well as col1
忽略这个问题的复杂性,我意识到我无法用原问题中描述的双子查询将a.code的值获取到子查询中
Select count(1) from (select distinct col1, col2 from mytable where code = a.code...)
--this doesn't work because the sub-query doesn't know what "a" is
所以最后我发现我可以作弊,把这些列合并起来:
Select count(distinct(col1 || col2)) from mytable where code = a.code...
这就是最终成功的方法
如果您使用的是固定长度的数据类型,则可以将其转换为二进制,从而非常容易和快速地完成此操作。假设documententid和DocumentSessionId都是int,因此都是4字节长…
SELECT COUNT(DISTINCT CAST(DocumentId as binary(4)) + CAST(DocumentSessionId as binary(4)))
FROM DocumentOutputItems
My specific problem required me to divide a SUM by the COUNT of the distinct combination of various foreign keys and a date field, grouping by another foreign key and occasionally filtering by certain values or keys. The table is very large, and using a sub-query dramatically increased the query time. And due to the complexity, statistics simply wasn't a viable option. The CHECKSUM solution was also far too slow in its conversion, particularly as a result of the various data types, and I couldn't risk its unreliability.
然而,使用上述解决方案几乎没有增加查询时间(与简单使用SUM相比),并且应该是完全可靠的!它应该能够帮助其他处于类似情况的人,所以我把它贴在这里。
希望这能起作用,我正在prima vista上写
SELECT COUNT(*)
FROM DocumentOutputItems
GROUP BY DocumentId, DocumentSessionId