我想选择我的网站内容的类别。其中大部分将由用户创建,因此我将处理表中许多类别的问题。我想在我的网站上尊重某些内容的趋势。我的解决方案是:
多亏了它,我在全球范围内从少量时间+最受欢迎的类别中获得了所有最受欢迎的类别。
(SELECT category, COUNT(*) AS number FROM data WHERE date BETWEEN ADDDATE(NOW(), INTERVAL -2 DAY) AND NOW() GROUP BY category)
UNION
(SELECT category, COUNT(*) AS number FROM data WHERE date < ADDDATE(NOW(), INTERVAL -2 DAY) GROUP BY category)
ORDER BY number DESC LIMIT 50
+----------+--------+
| category | number |
+----------+--------+
| 2 | 3 |
| 4 | 3 |
| 6 | 3 |
| 5 | 2 |
| 1 | 2 |
| 2 | 1 |
+----------+--------+
6 rows in set (0.00 sec)
注意类别(id 2)中有重复的内容,UNION DISTINCT(默认)不排除这个,因为它比较了两列的行,所以:
+----------+--------+
| category | number |
+----------+--------+
| 2 | 3 | //is not equal to
| 2 | 1 | //below values
+----------+--------+
//wont be excluded
我需要从类别列中选择不同值。
(数字仅用于排序目的,仅用于此查询)
答案 0 :(得分:0)
如果我正确理解您的问题,那么这应该是您需要的查询:
SELECT category
FROM (
SELECT category, COUNT(*) AS number
FROM data WHERE date BETWEEN ADDDATE(NOW(), INTERVAL -2 DAY) AND NOW()
GROUP BY category
UNION ALL
SELECT category, COUNT(*) AS number
FROM data WHERE date < ADDDATE(NOW(), INTERVAL -2 DAY)
GROUP BY category
ORDER BY number DESC
) s
GROUP BY category
ORDER BY MAX(number) DESC
LIMIT 50
我删除了两个用于进行联合查询的查询的括号(),因为UNION查询的ORDER BY将应用于两者。我还使用UNION ALL而不是UNION,因为类别在外部查询中再次分组,我会尝试使用UNION / UNION ALL来查看哪一个更快。
然后我按类别再次分组,并按类别的MAX(数字)排序,并仅保留前50行。