如何返回组中具有MIN / MAX值的行的ID?

时间:2013-03-07 18:53:06

标签: mysql sql greatest-n-per-group percona

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`

如何获取包含id值的行的MAX(`client_id`)

我在派生表的上下文中需要这个,例如

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`;

2 个答案:

答案 0 :(得分:0)

我在理解要求方面遇到了一些麻烦,但似乎是您正在寻找的。
不是最漂亮的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

An SQLfiddle for testing

答案 1 :(得分:0)

使用窗口函数查找每个组的最大值,然后使用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

我还添加了括号以澄清您的where声明。混合andor时,我总是使用括号来避免混淆和错误。

现在您已将mysql标记添加到语句中,但这不起作用。所以,这是一个特定于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

请注意,如果id将在此过程中转换为字符串。如果它有不同的类型,您可以将其转换回来。