我搜索了很多,但没有找到适合我的问题的解决方案。
我想做什么?
我在 MySQL 中有 2 个表: - 国家 - 货币 (我通过 CountryCurrency 将它们连接在一起 --> 由于多对多的关系)
有关工作示例,请参见:http://sqlfiddle.com/#!2/317d3/8/0
我想使用联接将两个表链接在一起,但我只想为每个国家/地区显示一行(有些国家/地区有多种货币,所以这是第一个问题)。
我找到了 group_concat 函数:
SELECT country.Name, country.ISOCode_2, group_concat(currency.name) AS currency
FROM country
INNER JOIN countryCurrency ON country.country_id = countryCurrency.country_id
INNER JOIN currency ON currency.currency_id = countryCurrency.currency_id
GROUP BY country.name
结果如下:
NAME ISOCODE_2 CURRENCY
Afghanistan AF Afghani
Åland Islands AX Euro
Albania AL Lek
Algeria DZ Algerian Dinar
American Samoa AS US Dollar,Kwanza,East Caribbean Dollar
但我现在想要的是将货币拆分为不同的列(货币 1、货币 2,...)。我已经尝试过像 MAKE_SET() 这样的函数,但这不起作用。
最佳答案
您可以使用 substring_index()
执行此操作。以下查询使用您的查询作为子查询,然后应用此逻辑:
select Name, ISOCode_2,
substring_index(currencies, ',', 1) as Currency1,
(case when numc >= 2 then substring_index(substring_index(currencies, ',', 2), ',', -1) end) as Currency2,
(case when numc >= 3 then substring_index(substring_index(currencies, ',', 3), ',', -1) end) as Currency3,
(case when numc >= 4 then substring_index(substring_index(currencies, ',', 4), ',', -1) end) as Currency4,
(case when numc >= 5 then substring_index(substring_index(currencies, ',', 5), ',', -1) end) as Currency5,
(case when numc >= 6 then substring_index(substring_index(currencies, ',', 6), ',', -1) end) as Currency6,
(case when numc >= 7 then substring_index(substring_index(currencies, ',', 7), ',', -1) end) as Currency7,
(case when numc >= 8 then substring_index(substring_index(currencies, ',', 8), ',', -1) end) as Currency8
from (SELECT country.Name, country.ISOCode_2, group_concat(currency.name) AS currencies,
count(*) as numc
FROM country
INNER JOIN countryCurrency ON country.country_id = countryCurrency.country_id
INNER JOIN currency ON currency.currency_id = countryCurrency.currency_id
GROUP BY country.name
) t
表达式 substring_index(currencies, ',' 2)
获取货币列表直到第二个。对于 American Somoa,这将是 'US Dollar,Kwanza'
。以 -1
作为参数的下一次调用采用列表的最后一个元素,即 'Kwanza'
,它是 currencies的第二个元素
.
另请注意,SQL 查询会返回一组明确定义的列。查询的列数不能可变(除非您通过 prepare
语句使用动态 SQL)。
关于mysql - SQL GROUP_CONCAT 拆分成不同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17836571/