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')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?