如何根据数据关系将表行转换为列

时间:2018-06-05 08:19:38

标签: mysql mysql-workbench

我想根据ID将列数据更改为列,如下表所示。 我必须在同一个id中连续显示5个单词,如果id少于5个单词,则其余列将填入' - '标志。我在这里使用mysql,我需要一种动态的方法来处理任何数量的数据。

我的表:

wordID   Word     Per     Sequence
  1      Kelly    68          1
  1      John     26          2
  2      Nisum    5.29        1
  2      Bily     14.1        2
  2      George   10          3
  2      Rihana   22          4
  3      August   72          1
  3      Rush     22          2
  3      Routh    95          3

所需表:

wordID   word    Per   word    Per    word    Per   word    Per   word   Per    
  1      Kelly   68    John    26      --     --     --     --    --    --
  2      Nisum   5.29  Bily    14.1   George  10    Rihana  22    --    --
  3      August  72    Rush    22     Routh   95     --     --    --    --  

2 个答案:

答案 0 :(得分:1)

以下查询将为您提供预期结果:

// $request is an instance of Request class
public function __construct(Request $request)
{
    $this->request = $request;
}

注意*:仅当您限制给定wordID允许的最大字数时,此选项才有用。即你的情况是5。

答案 1 :(得分:0)

此代码适用于此类问题: enter image description here