dpnhp20440 2016-08-10 10:52
浏览 347
已采纳

PHP MySQL查询 - 选择所有用户,但仅显示每个用户的最早登录时间

I want to be able to bring back the earliest logon time per user, so only 1 record (the earliest record) displays for each user

I've tried various ways of GROUP BY but can't seem to get it quite right (if that is actually the correct way of doing). username is the unique value which can be used to GROUP BY

Here's the code I'm currently working with..

SELECT username, name, logon, added FROM data WHERE (date(added) LIKE '$date') AND (logon = (SELECT MIN(logon) FROM data))

I've also tried (below) but only get one result back, only displaying one user

WHERE (date(added) LIKE '$date') AND logon = (SELECT MIN(logon) FROM data)

The first image is what I'm currently getting, the second image is how I want my results to display, please see below


Let me know if you require anymore information, I've tried to put as much as possible

Thanks, Tom


table

result


  • 写回答

3条回答 默认 最新

  • dongyan3562 2016-08-10 10:59
    关注

    You are close. Your query needs a correlation clause:

    SELECT d.*
    FROM data d
    WHERE date(d.added) = '$date' AND 
          d.logon = (SELECT MIN(d2.logon) FROM data d2 WHERE d2.name = d.name);
    

    Note: The logic for added is confusing. First, you should not use like with dates. And, for that matter, you should not be inserting parameter values into the string, you should be using query parameters. And, actually, I don't see the need for that column; your question doesn't mention added.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?