简体   繁体   中英

Get two columns from single table where one is max and group by that max column

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM