2012-01-05 126 views
1

有兩個具有相同結構的表:'imsc_storage_users'&'imsc_storage_users_archive'。MySQL結合來自同一方案表的聯合的結果

我現在的SELECT/UNION:

SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
FROM `imsc_storage_users` 
UNION DISTINCT 
SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
FROM `imsc_storage_users_archive` 
ORDER BY `correct` DESC,`minutes` ASC 

我得到這些結果:

+--------------+---------------------+-----------+---------+---------+------+---------+ 
| cli   | ts     | questions | answers | correct | last | minutes | 
+--------------+---------------------+-----------+---------+---------+------+---------+ 
| 111111111111 | 2011-12-22 11:13:57 |  30 |  29 |  14 | 30 | 1305.47 | 
| 222222222222 | 2011-12-15 13:39:16 |  26 |  24 |  13 | 24 | 15.67 | 
| 333333333333 | 2011-12-15 13:39:39 |  26 |  25 |  11 | 25 | 15.18 | 
| 444444444444 | 2011-12-15 13:39:39 |  25 |  21 |  11 | 25 | 280.53 | 
| 111111111111 | 2011-12-22 11:13:57 |  25 |  21 |  10 | 25 | 373.87 | 
| 555555555555 | 2011-12-19 15:46:15 |  11 |  10 |  5 | 10 |  3.8 | 
| 666666666666 | 2011-12-15 13:39:16 |  14 |  10 |  4 | 10 | 321.64 | 
| 777777777777 | 2011-12-19 08:34:36 |  15 |  11 |  4 | 13 | 474.66 | 

注意, '111111111111' 出現了兩次?

我希望它被合併,所以在結果集中我得到一行'111111111111',它合併/總和所有字段; 'questions'= >> 55 ....等'

什麼是正確的SQL?
性能在這裏不是問題。

謝謝!

+1

所以,當同樣的'cli'有'ts'不同的值?你如何將它們結合起來?'MIN'?'MAX'會發生什麼? – Lamak 2012-01-05 13:54:01

回答

7
SELECT `cli`,max(`ts`) AS ts, sum(`questions`) as questions, sum(`answers`) as answers,sum(`correct`) as correct,sum(`last`) as last,sum(`minutes`) as minutes 
FROM (
    SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
    FROM `imsc_storage_users` 
    UNION ALL 
    SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
    FROM `imsc_storage_users_archive` 
) AS baseview 
GROUP BY cli 
ORDER BY `correct` DESC,`minutes` ASC 
+1

請注意,UNION DISTINCT將消除兩個表之間的任何確切重複項,即使它們可能應包含在總和值中。 – 2012-01-05 13:56:24

+1

@MarkBannister先生,你有一隻鷹的眼睛!適當糾正。 – 2012-01-05 13:57:42

+0

Eugen:不完全(http://dev.mysql.com/doc/refman/5.0/en/union.html);嘗試UNION ALL。 – 2012-01-05 14:04:57

3

嘗試:

SELECT `cli`, 
     `ts`, 
     sum(`questions`), 
     sum(`answers`), 
     sum(`correct`), 
     sum(`last`), 
     sum(`minutes`) 
FROM (SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
     FROM `imsc_storage_users` 
     UNION ALL 
     SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
     FROM `imsc_storage_users_archive`) V 
group by `cli`, `ts` 
ORDER BY 5 DESC, 7 ASC 
相關問題