mysql计数不重叠的UNION结果

时间:2011-12-27 01:15:24

标签: mysql count duplicates union

好的,我有查询

(SELECT * FROM jokes WHERE flags < 5 AND (title LIKE ? OR joke LIKE ?) ORDER BY ups DESC,downs ASC)
UNION
(SELECT * FROM jokes WHERE flags < 5 AND (title LIKE ? OR joke LIKE ?) ORDER BY ups DESC,downs ASC)
UNION
(SELECT * FROM jokes WHERE flags < 5 AND (title LIKE ? OR joke LIKE ?) ORDER BY ups DESC,downs ASC)
 LIMIT 0, 30

我将使用COUNT(*)无限制地运行同样的事情

(SELECT COUNT(*) FROM jokes WHERE flags < 5 AND (title LIKE ? OR joke LIKE ?) ORDER BY ups DESC,downs ASC)
UNION
(SELECT COUNT(*) FROM jokes WHERE flags < 5 AND (title LIKE ? OR joke LIKE ?) ORDER BY ups DESC,downs ASC)
UNION
(SELECT COUNT(*) FROM jokes WHERE flags < 5 AND (title LIKE ? OR joke LIKE ?) ORDER BY ups DESC,downs ASC)

基本上我想做的是获得总结果的数量(没有限制),并获得有限的列表。

我遇到的问题是,当我运行计数查询时,我得到的数字比我得到的结果要大。我猜测的原因是当我得到结果时,它会过滤掉所有重叠的行,其中计数只计算每个,因为我手动必须添加它们。

关于如何清理整个过程的任何想法?

另外,请注意,select语句的数量会动态变化,但我希望有一种方法可以获得一个重复的一般计数。

感谢。

1 个答案:

答案 0 :(得分:1)

对于伯爵来说这是怎么回事:

SELECT COUNT(DISTINCT Id)
FROM (SELECT Id From jokes WHERE flags < 5 AND (title LIKE ? OR joke LIKE ?) 
      UNION
      SELECT Id From jokes WHERE flags < 5 AND (title LIKE ? OR joke LIKE ?) 
      UNION
      SELECT Id From jokes WHERE flags < 5 AND (title LIKE ? OR joke LIKE ?)) t

这应该给你一个唯一的计数,并且还注意到我已经删除了它,因为它不值得为计数查询计算。