2015-12-06 53 views
1

我有兩個疑問,我想結合成1。然而,我發現了一個錯誤:結合2次不同的查詢到一個

//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

你是什麼意思結合起來?你能給出這兩個查詢結果的例子嗎?你想如何合併這些結果? 在MySQL中,有一個UNION語句,它將合併多個查詢的結果。但是,結果需要具有相同的列。 –

回答

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

+0

非常好。在我意識到這是短暫的日期之前,讓我感到困惑的是在那裏名爲dt的列。 – frosty