合并来自MySQL / MariaDB中不同行中同一列的两个单元格的数据

时间:2016-03-26 17:21:07

标签: mysql sql mariadb

我无法搜索这个问题的答案,因为我对术语和SQL缺乏了解,尽管我知道它可能存在。

我有一个包含以下表格的数据库:
desc pkm;

+-----------------+---------------+------+-----+---------+-------+
| Field           | Type          | Null | Key | Default | Extra |
+-----------------+---------------+------+-----+---------+-------+
| pkm_code        | int(11)       | NO   | PRI | NULL    |       |
| pkm_name        | varchar(32)   | NO   | UNI | NULL    |       |
| pkm_category    | varchar(32)   | NO   |     | NULL    |       |
| pkm_description | varchar(1280) | NO   |     | NULL    |       |
| pkm_weight      | float         | NO   |     | NULL    |       |
| evolution_code  | int(11)       | YES  | MUL | NULL    |       |
+-----------------+---------------+------+-----+---------+-------+

desc poketype;

+---------------------+------------+------+-----+---------+-------+
| Field               | Type       | Null | Key | Default | Extra |
+---------------------+------------+------+-----+---------+-------+
| pkm_code            | int(11)    | NO   | PRI | NULL    |       |
| type_code           | int(11)    | NO   | PRI | NULL    |       |
| poketype_is_primary | tinyint(1) | NO   |     | NULL    |       |
+---------------------+------------+------+-----+---------+-------+

desc type;

+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| type_code | int(11)     | NO   | PRI | NULL    |       |
| type_name | varchar(32) | NO   | UNI | NULL    |       |
+-----------+-------------+------+-----+---------+-------+

到目前为止,我有以下SQL命令:

SELECT pkm.pkm_code, pkm.pkm_name,type.type_name FROM poketype
    JOIN pkm ON pkm.pkm_code=poketype.pkm_code
    JOIN type ON poketype.type_code=type.type_code
    WHERE pkm.pkm_code<=151
    ORDER BY pkm_code;

在单独的行中显示主要和次要类型 对于双型口袋妖怪,我如何让两种类型显示在同一行?

我目前的成绩:

+-----------+-------------+-----------+
| pkm_code  | pkm_name    | type_name |
+-----------+-------------+-----------+
| 1         | Bulbasaur   | grass     |
| 1         | Bulbasaur   | poison    |

期望的结果:

+-----------+-------------+-------------+
| pkm_code  | pkm_name    | type_name   |
+-----------+-------------+-------------+
| 1         | Bulbasaur   | grass,poison|

(是的,bulbasaur是双重类型。我也很惊讶!)

1 个答案:

答案 0 :(得分:2)

使用mysql的group_concat() function将来自不同记录的值组合在一个值中:

SELECT pkm.pkm_code, pkm.pkm_name, group_concat(type.type_name) as typename FROM poketype
    JOIN pkm ON pkm.pkm_code=poketype.pkm_code
    JOIN type ON poketype.type_code=type.type_code
    WHERE pkm.pkm_code<=151
    GROUP BY pkm.pkm_code, pkm.pkm_name;