如何制作mysql子查询

时间:2013-07-24 07:23:46

标签: mysql sql

我有一张大表,现在该表按日期细分为几个

e.g。

原始表

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

所以我想知道如何通过一个sql显示这种格式

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

最佳效率点。感谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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。

答案 2 :(得分:0)

子查询的一个例子:

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

将column_name设为customerNumber和 column_name1作为checkNumber和 column_number为amo