简体   繁体   中英

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?

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;

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 .

Use window functions to find the max for each group and then a where clause to select the row with the maximum:

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. When mixing and and or , I always use parentheses to avoid possible confusion and mistakes.

Now that you've added the mysql tag to your statement, this won't work. So, here is a MySQL-specific solution:

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 it has a different type, you can convert it back.

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