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 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出