简体   繁体   English

将多行合并为一个MySQL

[英]Combine multiple rows into one MySQL

I need some help. 我需要协助。 I googled for solution, but I didn't found one. 我用谷歌搜索解决方案,但我没找到一个。

I have three tables: 我有三张桌子:

langs
(int) id | (varchar) language
    1    |       English
    2    |        Latin
    3    |      Esperanto
   ...   |         ...

keys
(int) id | (varchar) keys
    1    |       dog
    2    |       cat
   ...   |       ...

value
(int) id | (int) key_id | (int) lang_id | (varchar) value
    1    |       1      |        1      |        Dog
    2    |       1      |        2      |       Canis
    3    |       2      |        1      |        Cat
    4    |       2      |        2      |       Felis
    5    |       2      |        3      |        Kato
   ...   |      ...     |       ...     |        ...

and I want to get the result: 我想得到结果:

key_id |  keys  |  English  |  Latin  |  Esperanto  
   1   |  dog   |    Dog    |  Canis  |    NULL
   2   |  cat   |    Cat    |  Felis  |    Kato
  ...  |  ...   |    ...    |   ...   |    ...

merging rows with equal key_id . 合并具有相同key_id行。 I know I can try to make it with multiple JOINs, but it's slow and I must know the exact number of different langs . 我知道我可以尝试使用多个JOIN,但它很慢,我必须知道不同langs的确切数量。

Thanks in advance. 提前致谢。 :) :)

SELECT CONCAT(
  ' SELECT `value`.`key_id`,'
,        '`keys`.`keys`,'
,         GROUP_CONCAT(
           'GROUP_CONCAT(IF(`value`.`lang_id`=',id,',`value`.`value`,NULL))'
          ,   ' AS `', REPLACE(language, '`', '``'), '`'
          )
, ' FROM `keys` JOIN `value` ON `value`.`key_id` = `keys`.`id`'
, ' GROUP BY `value`.`key_id`'
)
INTO @sql
FROM `langs`;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

You are essentially looking at a pivot table. 您实际上是在查看数据透视表。 It Is doable, though the code is a bit cumbersome. 它是可行的,虽然代码有点麻烦。

one source: http://www.artfulsoftware.com/infotree/queries.php#78 一个来源: http//www.artfulsoftware.com/infotree/queries.php#78

In the end though most any mysql solution will require either some wizardry with stored procedures or... hardcoding what languages you return. 最后,虽然大多数mysql解决方案都需要一些带有存储过程的魔法,或者......硬编码你返回的语言。

Pivot tables are one area that mysql doesn't shine in. 数据透视表是mysql没有发光的一个领域。

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

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