2013-07-24 57 views
-1

我有一个大的表,现在该表被细分为几个日期如何使mysql子查询

例如,

原始表

UserLoginTable 
+---------+------------+---------+ 
| UserID | LoginTime | others | 
+---------+------------+---------+ 
| 1  | 2013-03-12 | .... | 
+---------+------------+---------+ 
| 2  | 2013-05-12 | .... | 
+---------+------------+---------+ 
| 1  | 2013-06-12 | .... | 
+---------+------------+---------+ 
| ... | ...  | .... | 
+---------+------------+---------+ 

现在的表是:

UserLoginTable_Date(yyyyMM) 

UserLoginTable_201303

+---------+------------+---------+ 
| UserID | LoginTime | others | 
+---------+------------+---------+ 
| 1  | 2013-03-12 | .... | 
+---------+------------+---------+ 

UserLoginTable_201304

+---------+------------+---------+ 
| UserID | LoginTime | others | //this table is not have UserID=1 
+---------+------------+---------+ 
| 2  | 2013-04-01 | .... | 
+---------+------------+---------+ 

我曾经

select count(*) from UserLoginTable_201307 where UserID=1 
select count(*) from UserLoginTable_201306 where UserID=1 
... 

所以我想Kown如何通过一个SQL

+--------------+ 
| UserInYear | 
+--------------+ 
| 201303  | //here dose find User in 201304 
+--------------+ 
| 201306  | 
+--------------+ 
| ....  | 
+--------------+ 

的最佳效率点,以示对这种格式。谢谢。

回答

0

尝试使用union all如下

select count(*) as UserInYear from UserLoginTable_201307 where UserID=1 
union all 
select count(*) from UserLoginTable_201306 where UserID=1 

注意union all不会消除重复。如果您不想复制,则必须使用union insetad。

+0

谢谢,你快速 – zt9788

+0

我很抱歉,我也想知道,如何显示结果是UserInYear(不计数),只是日期(201307或201306 ...)如果计数> 0 – zt9788

+0

尝试添加一些东西像''有'count(distinct date)> 0'在'where'子句下方 – Parado

0

使用UNION ALL为:

SELECT COUNT(*) AS UserInYear FROM UserLoginTable_201307 WHERE UserID = 1 
UNION ALL 
SELECT COUNT(*) FROM UserLoginTable_201306 WHERE UserID = 1 

如果没有为UserInYear重复值,任何一年UNION ALL将显示所有,而UNION不会显示。所以使用UNION ALL

+0

感谢,但Parado快,那么你!! :) – zt9788

+0

@ zt9788 - 不是问题,但实际上我比他快。 (5秒):) – hims056

+0

@ hims056海事组织你的代码不起作用,你确定你有一个别名在正确的地方? – Parado

0

子查询的一个例子:

SELECT column_name, column_name1, column_number 
FROM their_table 
WHERE column_number = (SELECT MAX(column_number) FROM the_other_table); 

假设列名作为customerNumber之和 column_name1作为checkNumber和 COLUMN_NUMBER栏作为AMO