使用左联接和分组依据重命名来自查询的重复结果

时间:2019-04-29 10:11:06

标签: mysql group-by mysql-5.5

我有这个查询:

SELECT 
category,
description
FROM `players` 
INNER JOIN orders ON orders.id_player = players.player
GROUP BY id_p

这是结果:

category           description
1                  tv
1                  radio
1                  computer
2                  hamburger

我想要得到这样的东西:

category        description
1                 tv
-                 radio
-                 computer
2                 hamburger

如何更改查询? 谢谢

*进行数据库更改

2 个答案:

答案 0 :(得分:0)

ROW_NUMBER()CASE结合使用可以达到预期的结果:

SELECT (CASE WHEN ROW_NUMBER() OVER 
        (PARTITION BY order_player ORDER BY (SELECT NULL)) = 1 
       THEN order_player ELSE '-' END
       ) AS order_player,
    description
FROM `players` 
INNER JOIN orders ON orders.id_player = players.player
GROUP BY id_p

答案 1 :(得分:0)

5.5

使用此模式:

实时测试:https://www.db-fiddle.com/f/dicEcARLUJpYLcWTULsb4n/0

select category, description
from 
(
  select
      case when t.category <> @category then 
          t.category
      else
          '-'
      end as category,
      description,
      @category := category
  from tbl t cross join (select @category := '') x
  order by t.category, description
) y

输出:

|    category | description |
|-------------|-------------|
| electronics |    computer |
|           - |       radio |
|           - |          tv |
|        food |   hamburger |