doudi4621 2015-06-17 17:59 采纳率: 0%
浏览 236
已采纳

从单个表中获取两列,其中一列是最大值,另一列是最大列

Table: XYZ
+----+-----------+--------+---------+
| ID | parent_ID | status | user_ID |
+----+-----------+--------+---------+
| 1  | 432       | public | 23      |
| 5  | 432       | public | 1       |
| 10 | 432       | public | 14      |
| 24 | 432       | public | 4       |
+----+-----------+--------+---------+

If this is the scenario where ID is an auto increment field I can grab the last ID by the following query:

SELECT MAX(ID)
FROM XYZ
WHERE parent_ID = 432
   AND status = 'public'

How can I grab the two fields: ID, and user_ID using a single query so that I can have the following result:

array(
   'ID' => 24
   'user_ID' => 4
)

That means the Maximum value of ID where parent_ID is 432 and user_ID of that row of ID.

I have seen this answer and tried, but in my case I don't have group by ID and max ID different. In my case everything is ID. I know I can have them all, then can run a foreach to grab the max one in PHP way, but I think a single SQL query is much faster here.

Any help and suggestion would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • douyuan4697 2015-06-17 18:03
    关注

    Try this:

    SELECT ID, user_ID
    FROM XYZ AS x
    INNER JOIN (SELECT MAX(ID) AS maxID
                FROM XYZ
                WHERE parent_ID = 432 AND status = 'public') t
    ON x.ID = t.maxID
    

    Or, alternatively:

    SELECT ID, user_ID
    FROM XYZ 
    WHERE ID = (SELECT MAX(ID) AS maxID
                FROM XYZ
                WHERE parent_ID = 432 AND status = 'public')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写