日期:2014-05-16  浏览次数:20773 次

求一条SELECT语句,有趣,常用,望高手解答
有一张表
t_test

id   int4,   主健
user_id   int4,  
visit_date   timestamp

要求输出记录,但是user_id相同的记录并且visit_date里同一天的数据只输出一条
而且,   排序是按   user_id   升序,   visit_date   降序

insert   into   t_test   values(1,   13,   timestamp   '2007-4-12   09:30:21 ');
insert   into   t_test   values(2,   13,   timestamp   '2007-4-12   12:31:32 ');
insert   into   t_test   values(3,   13,   timestamp   '2007-4-12   23:11:00 ');
insert   into   t_test   values(4,   13,   timestamp   '2007-5-23   07:41:42 ');
insert   into   t_test   values(5,   15,   timestamp   '2007-4-12   23:51:52 ');

结果应该只有3条输出。

------解决方案--------------------

select distinct [user_id],visit_date from t_test
输出:
13 2007-04-12 00:00:00.000
13 2007-05-23 00:00:00.000
15 2007-04-12 00:00:00.000
我把你日期后的时间去掉了.
还有,如果你要同时输出id的话,我感觉是不能只输出3条信息的,因为id是主键,每条信息都对应不同的id,可以group user_id,visit_date,但是你不能同时group id
------解决方案--------------------
select a.* from t_test a,
(select id ,user_id ,substr(visit_date,0,length(visit_date)-6) as visit_date2 from t_test
group by user_id,substr(visit_date,0,length(visit_date)-6) ) b
where a.id=b.id
and a.substr(visit_date,0,length(visit_date)-6)=b.visit_date2
order by a.user_id asc,a.visit_date desc
应该可以,不会用date
------解决方案--------------------
不知道你的id是否取最新插入的。
以下试试,参考:
select max(id) as id,user_id,visit_date from t_test group by concat(user_id,left(visit_date,10)) order by user_id asc,id desc;
------解决方案--------------------
select distinct [user_id],visit_date from t_test order by user_id asc,id desc;
------解决方案--------------------
基础知识不扎实

看这条语句:
mysql> select max(id),user_id,visit_date from t_test group by user_id,date(visit
_date) order by user_id,visit_date desc;

结果:
+---------+---------+---------------------+
| max(id) | user_id | visit_date |
+---------+---------+---------------------+
| 4 | 13 | 2007-05-23 07:41:42 |
| 3 | 13 | 2007-04-12 09:30:21 |
| 5 | 15 | 2007-04-12 23:51:52 |
+---------+---------+---------------------+
3 rows in set (0.01 sec)