1. mysql查询
两张表:
user用户表:id (主键,自增),name
buy 购买记录表: id (主键,自增),userid(关联user表的id),time(购买时间)
要求:假设每个用户都有购买记录,查询每个用户的第一次购买记录。
1)用最早购买时间作为判断条件
select b.userid,min(u.`name`) as `name`,min(b.`time`) as `time`
from user u inner join buy b
on u.id=b.userid
group by b.userid;
2) 用每个用户第一条购买记录id做判断。
select b.userid,u.`name`,b.`time`
from user u inner join
(select * from buy where id in
(select min(id) from buy group by
userid)) b
on u.id=b.userid;
如果想将没有购买记录的客户也列出来,那么上述两个语句中的inner join请该为left join。
网友评论