题目描述:sql语句查询每个用户最近一天登录的日子,用户的名字,以及用户用的设备的名字,并且查询结果按照user的name升序排序。
select 子句中只能存在以下三种元素:常数、聚合函数、group by子句指定列(聚合键)
所以下面这么写法错误:
1 2 3 4 5 6 7 8 |
select u.name as u_n, c.name as c_n, max(l.date) as d #列名c.name as c_n不能包含
from login as l
inner join user as u
on l.user_id=u.id
inner join client as c
on l.client_id=c.id
group by u.name
order by u.name asc
|
解释:group by中只包含了u.name,但不包括c.name,因此c.name 不能出现在select里。
正确的写法(多列名IN):
复制代码1 2 3 4 5 6 7 |
select u.name as u_n,
c.name asc_n,
l.date
from login l join user u on l.user_id=u.id
join client c on l.client_id=c.id
where (l.user_id,l.date) in (select user_id,max(date) from login group by user_id)
order by u_n
|
SELECT a.date,COUNT(*)
FROM(
SELECT l.*,d.date 首次登录时间
FROM login l
LEFT JOIN(
SELECT user_id,MIN(DATE) DATE
FROM login
GROUP BY user_id)d
ON l.user_id=d.user_id) a
GROUP BY a.date
HAVING a.date=a.首次登录时间;
————————————————
版权声明:本文为CSDN博主「koding7879」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/koding7879/article/details/108985341