MYSQL UNION GROUP BY

时间:2015-09-16 16:23:04

标签: mysql select group-by union-all

我正在做这个选择声明:

int nextKeyboardInt(){
    while(!scanner.hasNextInt()){
        scanner.next();
    }
    return scanner.nextInt();
}
a[i][j] = nextKeyboardInt();
//another code//
int anotherInt = nextKeyboardInt();

这个选择得到了这个:

enter image description here

我正试图以SELECT * FROM ( SELECT COUNT(t.text) as count, COUNT(DISTINCT(t.from_user_id)) as usercount, DATE_FORMAT(t.created_at,'%Y-%m-%d %H:00') datepart FROM TABLE1 t WHERE t.created_at >= '2015-08-12 00:00:00' AND t.created_at <= '2015-08-13 18:30:00' AND t.eliminar IS NULL GROUP BY datepart) as t UNION ALL SELECT * FROM ( SELECT COUNT(b.id) as count, COUNT(DISTINCT(b.from_user_id)) as usercount, DATE_FORMAT(b.created_at,'%Y-%m-%d %H:00') datepart FROM TABLE2 b WHERE b.created_at >= '2015-08-12 00:00:00' AND b.created_at <= '2015-08-13 18:30:00' AND b.eliminar IS NULL GROUP BY datepart) as x GROUP BY datepart 分组查看,但我不知道,不知道我做错了什么?

TABLE2只有(id,from_user_id,eliminar)并且除了datepart之外都是NULL,在这一行中我整个2015年都是按日和小时,格式与TABLE1相同

1 个答案:

答案 0 :(得分:0)

解决:

SELECT DISTINCT * FROM (
SELECT COUNT(t.text) as count, COUNT(DISTINCT(t.from_user_id)) as usercount, DATE_FORMAT(t.created_at,'%Y-%m-%d %H:00') datepart 
FROM TABLE1 t WHERE t.created_at >= '2015-08-12 00:00:00' AND t.created_at <= '2015-08-13 18:30:00' AND t.eliminar IS NULL 
GROUP BY datepart
UNION ALL
SELECT COUNT(t.id) as count, COUNT(DISTINCT(t.from_user_id)) as usercount, DATE_FORMAT(t.created_at,'%Y-%m-%d %H:00') datepart 
FROM TABLE2 t WHERE t.created_at >= '2015-08-12 00:00:00' AND t.created_at <= '2015-08-13 18:30:00' AND t.eliminar IS NULL 
GROUP BY datepart) as x GROUP BY datepart ORDER BY datepart