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'
如何使用单个查询获取两个字段:ID
和 user_ID
,以便获得以下结果:
array(
'ID' => 24
'user_ID' => 4
)
这意味着 ID
的最大值(其中 parent_ID
为 432)以及该行 ID
的 user_ID
。
我见过this answer并尝试过,但就我而言,我的 group by ID
和 max ID
没有不同。就我而言,一切都是ID
。我知道我可以拥有所有这些,然后可以运行 foreach 以 PHP 方式获取最大的一个,但我认为单个 SQL 查询在这里要快得多。
任何帮助和建议将不胜感激。
最佳答案
试试这个:
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
或者,另一种选择:
SELECT ID, user_ID
FROM XYZ
WHERE ID = (SELECT MAX(ID) AS maxID
FROM XYZ
WHERE parent_ID = 432 AND status = 'public')
关于php - 从单个表中获取两列,其中一列是最大值,并按该最大值列进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30898956/