GROUP BY函数返回第一个结果

时间:2017-01-03 21:50:43

标签: mysql sql

这是我的MySQL查询及其结果,我想为'function'的每个值获取'priority'的第一个结果,从而得到下面的结果

但是,“SELECT函数,FIRST(优先级)... GROUP BY函数”类型的语法不存在,你知道怎么做吗?

SELECT
  function,
  priority
FROM challenge_access_rule
WHERE 10 = challenge_access_rule.challenge_id
      AND (
        rule = 'everybody'
        OR (rule = 'friends' AND 1)
      )
UNION
SELECT
  function,
  isRestriction AS priority
FROM challenge_access_user
WHERE 10 = challenge_access_user.challenge_id AND challenge_access_user.user_id = 2
ORDER BY ABS(priority)

-- RESULT --
emitInstance      |  0
emitDeal          |  0
emitDealInstance  |  1
emitDeal          |  100
emitDealInstance  |  -100
vote              |  -100
emitDeal          |  -200
view              |  -200
interact          |  -200

-- DESIRED RESULT --
emitInstance      |  0
emitDeal          |  0
emitDealInstance  |  1
vote              |  -100
view              |  -200
interact          |  -200

谢谢, 巴斯蒂安

2 个答案:

答案 0 :(得分:2)

首先,我会将您当前的查询简化为:

SELECT car.function, car.priority
FROM challenge_access_rule car
WHERE 10 = car.challenge_id AND
      ( car.rule in ('everybody', 'friends') or
        car.user_id = 2
      )
ORDER BY ABS(car.priority);

然后,如果您想要优先级的绝对值的最小值,那么您可以使用聚合和substring_index() / group_concat()技巧:

SELECT car.function,
       substring_index(group_concat(car.priority order by ABS(car.priority)), ',', 1) as priority
FROM challenge_access_rule car
WHERE 10 = car.challenge_id AND
      ( car.rule in ('everybody', 'friends') or
        car.user_id = 2
      )
GROUP BY car.function;

case表达式:

SELECT car.function,
       (case when min(car.priority) = - min(abs(car.priority))
             then - min(abs(car.priority))
             else min(car.priority)
        end) as priority
FROM challenge_access_rule car
WHERE 10 = car.challenge_id AND
      ( car.rule in ('everybody', 'friends') or
        car.user_id = 2
      )
GROUP BY car.function;

答案 1 :(得分:0)

此代码有效!

感谢Gordon

SELECT function,
substring_index(group_concat(priority ORDER BY ABS(priority)), ',', 1)
FROM (
       SELECT
         function,
         priority
       FROM challenge_access_rule
       WHERE 10 = challenge_access_rule.challenge_id
             AND (
               rule = 'everybody'
               OR (rule = 'friends' AND 1) -- 'AND 1' edit after
             )
       UNION
       SELECT
         function,
         isRestriction AS priority
       FROM challenge_access_user
       WHERE 10 = challenge_access_user.challenge_id AND challenge_access_user.user_id = 2
       ORDER BY ABS(priority)
     ) AS toto
GROUP BY function