简体   繁体   English

如何合并 mysql 表中的行

[英]How to merge rows in a mysql table

I have a table where each row contains a temperature and the weather condition such as:我有一个表格,其中每一行都包含温度和天气状况,例如:

temp  condition
17    cloudy
25    sunny
22    cloudy
41    sunny
12    showers
38    sunny

I am restricted for storage space so I wanted to cut down the size of this table.我的存储空间有限,所以我想缩小这张桌子的大小。 How can I merge the same weather conditions into one row where the temperature column has the different temperatures with a seperator such as "|"?如何将相同的天气条件合并到一行中,其中温度列具有不同的温度,并带有“|”之类的分隔符?

Once merged the table would look like:合并后,表格将如下所示:

temp       condition
17|22      cloudy
25|41|38   sunny
12         showers

I have changed the data type of the temp column to varchar to allow it to store the new format, but not sure how I can merge the rows now.我已将 temp 列的数据类型更改为 varchar 以允许它存储新格式,但不确定现在如何合并行。

I want to overwrite this table with the new format as opposed to just combining it on select query.我想用新格式覆盖这个表,而不是仅仅在 select 查询中组合它。 This will help to lower the file size and make it faster to run queries.这将有助于减小文件大小并加快查询运行速度。 If this cannot be done directly on mysql (phpmyadmin) then I would prefer to do this via a PHP script.如果这不能直接在 mysql (phpmyadmin) 上完成,那么我更愿意通过 PHP 脚本来完成。

You can use group_concat() to generate the results:您可以使用group_concat()生成结果:

select
    group_concat(temp delimiter '|') temp,
    condition
from mytable
group by condition

As for overwriting the table, you would need to proceed in several steps:至于覆盖表格,您需要分几个步骤进行:

  • create a new table to store the results of the query创建一个新表来存储查询结果

  • feed it with the above query用上面的查询喂它

  • drop the original table删除原始表

  • rename the new table to the original name将新表重命名为原始名称

I would not actually recommend going this direction.我实际上不建议朝这个方向发展。 The tiny space gain that you will get will be overwhelmed by the drawbacks that storing data as delimited lists implies.您将获得的微小空间增益将被将数据存储为分隔列表所暗示的缺点所淹没。 I would recommend the following reading: Is storing a delimited list in a database column really that bad?我建议阅读以下内容:在数据库列中存储分隔列表真的那么糟糕吗? , and a good second thought. , 和一个很好的第二个想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM