我有2个查询,我想将其合并为1.但是,我收到了错误:
//first query: SELECT @rownum := @rownum +1 `index` , t. * FROM ipAll t, ( SELECT @rownum :=0 ) r //second query: SELECT DISTINCT COUNT( ip ) , SUM( views ) , DATE FROM ipAll WHERE date LIKE '%-12-%' GROUP BY DATE ORDER BY DATE ASC LIMIT 31 // combined query: (Totally wrong. How do I fix this?) SELECT @rownum := @rownum +1 `index` , DISTINCT COUNT( ip ) , SUM( views ) , DATE FROM ipAll t, ( SELECT @rownum :=0 ) r WHERE date LIKE '%-12-%' GROUP BY DATE ORDER BY DATE ASC LIMIT 31
答案 0 :(得分:2)
我建议删除distinct
。
我们假设您的表格包含以下内容:
| dt | ip | views |
|----------------------------|---------|-------|
| December, 01 2015 00:00:00 | 1.1.1.1 | 100 |
| December, 01 2015 00:00:00 | 2.2.2.2 | 10 |
| December, 02 2015 00:00:00 | 3.3.3.3 | 4 |
| December, 01 2014 00:00:00 | 1.1.1.1 | 100 |
| November, 01 2015 00:00:00 | 1.1.1.1 | 1 |
| November, 01 2015 00:00:00 | 2.2.2.2 | 2 |
查询:
SELECT
@rownum := @rownum +1 `index`,
COUNT( ip ), SUM( views ) , dt
FROM ipAll, ( SELECT @rownum :=0 ) r
WHERE dt LIKE '%-12-%'
GROUP BY dt
ORDER BY dt ASC
LIMIT 31;
将导致:
| index | COUNT( ip ) | SUM( views ) | dt |
|-------|-------------|--------------|----------------------------|
| 3 | 1 | 100 | December, 01 2014 00:00:00 |
| 1 | 2 | 110 | December, 01 2015 00:00:00 |
| 2 | 1 | 4 | December, 02 2015 00:00:00 |
获得类似(不相同)结果的另一种方法是:
select @rownum := @rownum +1 `index`, main.*
from ( SELECT @rownum :=0 ) r, (
SELECT COUNT( ip ), SUM( views ) , dt
FROM ipAll
WHERE dt LIKE '%-12-%'
GROUP BY dt
LIMIT 31
) main
ORDER BY dt ASC
结果将是:
| index | COUNT( ip ) | SUM( views ) | dt |
|-------|-------------|--------------|----------------------------|
| 1 | 1 | 100 | December, 01 2014 00:00:00 |
| 2 | 2 | 110 | December, 01 2015 00:00:00 |
| 3 | 1 | 4 | December, 02 2015 00:00:00 |
SQLFiddle示例:http://sqlfiddle.com/#!9/beb98/3