[英]How to return an ID for the row that has MIN/MAX value within a group?
SELECT
MAX(`client_id`) `client_id`
FROM
`phrases`
WHERE
`language_id` = 1 AND
`client_id` = 1 OR
`client_id` IS NULL
GROUP BY
`language_phrase_id`
How do I get the id
for the row that holds MAX(`client_id`)
value? 如何获取包含
MAX(`client_id`)
值的行的id
?
I need this in the context of derived table, eg 我需要在派生表的上下文中,例如
SELECT
`p2`.`phrase`
FROM
(SELECT `language_phrase_id`, MAX(`client_id`) `client_id` FROM `phrases` WHERE `language_id` = 1 AND `client_id` = 1 OR `client_id` IS NULL GROUP BY `language_phrase_id`) `p1`
INNER JOIN
`phrases` `p2`
ON
`p2`.`language_id` = 1 AND
`p1`.`language_phrase_id` = `p2`.`language_phrase_id` AND
`p1`.`client_id` = `p2`.`client_id`;
I had a bit of trouble understanding the requirements, but this seems to be what you're looking for. 我在理解需求时遇到了一些麻烦,但这似乎正是您要寻找的。
Not the most beautiful SQL and I'm sure it can be simplified, but a starting point; 不是最漂亮的SQL,我敢肯定它可以简化,而是一个起点。
SELECT p1.id, p1.phrase
FROM phrases p1
LEFT JOIN `phrases` p2
ON p1.language_id=p2.language_id
AND p1.language_phrase_id=p2.language_phrase_id
AND p1.client_id IS NULL and p2.client_id = 1
WHERE p2.id IS NULL AND p1.language_id=1
AND (p1.client_id=1 or p1.client_id IS NULL)
GROUP BY p1.language_phrase_id
Use window functions to find the max for each group and then a where
clause to select the row with the maximum: 使用窗口函数查找每个组的最大值,然后使用
where
子句选择具有最大值的行:
select p.*
from (SELECT p.*, max(client_id) partition by (language_phrase_id) as maxci
from phrases p
WHERE (`language_id` = 1 AND `client_id`= 1) or
`client_id` IS NULL
) p
where client_id = maxci
I also added parentheses to clarify your where
statement. 我还添加了括号以阐明您的
where
语句。 When mixing and
and or
, I always use parentheses to avoid possible confusion and mistakes. 混合
and
和or
,我总是使用括号以避免可能出现的混乱和错误。
Now that you've added the mysql
tag to your statement, this won't work. 现在,您已将
mysql
标记添加到语句中,这将不起作用。 So, here is a MySQL-specific solution: 因此,这是一个特定于MySQL的解决方案:
select language_phrase_id,
substring_index(group_concat(id order by client_id desc), ',', 1) as max_id
from phrases
group by phrases p
Note that this if id
will get converted to a character string in this process. 请注意,此if
id
将在此过程中转换为字符串。 If it has a different type, you can convert it back. 如果类型不同,则可以将其转换回来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.