查询仅获取每个唯一列ID的3条记录

时间:2014-03-17 00:22:17

标签: mysql

我有一个列出食物类型的表格,我想运行查询以返回最多12种食物,但每个类别不超过3种。我可以在一个查询中执行此操作吗?

category    food    tastyFactor id
seafood     fish    100         1
seafood     prawns  150         2
seafood     crab    50          3
seafood     oysters 300         4
meat        chicken 20          5
meat        pork    100         6
meat        lamb    40          7
meat        beef    50          8
vegetables  carrot  10          9
vegetables  cabbage 300         10
vegetables  potato  75          11
vegetables  parsnip 500         12

食物应该由tastyFactor订购(结果集中应该出现的最低数字)。

在我的例子中,结果应该是:

carrot
chicken
lamb
beef
crab
potato
fish
prawns
cabbage

4 个答案:

答案 0 :(得分:0)

您可以使用UNION将多个查询与相同内容合并:

SELECT food FROM (
  (SELECT category, food, tastyfactor, id FROM table  
    WHERE category = 'seafood' LIMIT 3)
  UNION
  (SELECT category, food, tastyfactor, id FROM table 
    WHERE category = 'meat' LIMIT 3)
  UNION
  (SELECT category, food, tastyfactor, id FROM table 
    WHERE category = 'vegetables' LIMIT 3)
) AS food_from_cateogry ORDER BY tastyfactor

答案 1 :(得分:0)

假设您事先不知道类别的数量,您仍然可以进行查询。您需要首先枚举每个类别中的值。虽然您可以使用变量,但我会为枚举选择相关的子查询方法:

select ft.food
from (select ft.*,
             (select count(*)
              from FoodTypes ft2
              where ft2.category = ft.category and
                    (ft2.tastyFactor < ft.tastyFactor or
                     ft2.tastyFactor = ft.tastyFactor and ft2.id <= ft.id
                    )
             ) as cat_seqnum
      from FoodTypes ft
     ) ft
where cat_seqnum <= 3
order by TastyFactor
limit 12;

答案 2 :(得分:0)

SELECT x.food
  FROM my_table x
  JOIN my_table y
    ON y.category = x.category
   AND y.tastyfactor <= x.tastyfactor
 GROUP
    BY x.category
     , x.food
HAVING COUNT(*) <= 3
 ORDER
    BY x.tastyfactor
     , x.food;

请注意,您可能想要更多地考虑如何处理关系。

答案 3 :(得分:0)

可以使用GROUP_CONCAT和FIND_IN_SET的组合来完成。对于大型集合,我认为处理会降级,但对于较小的数据则相当简单。

SELECT a.food
      ,b.category
      ,find_in_set(a.food, foods) ranking
  FROM food a
       INNER JOIN (
          SELECT category,
                 GROUP_CONCAT(food ORDER BY tastyFactor DESC) foods
            FROM food
           GROUP BY category
       ) b ON a.category = b.category
 WHERE FIND_IN_SET(a.food, foods) <= 3
 ORDER BY category
         ,ranking ASC

Fiddle