[英]SQL GROUP_CONCAT split in different columns
我搜索了很多,但没有找到解决问题的正确方法。
我想做什么?
我在MySQL中有两个表: - 国家 - 货币(我通过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)
将货币列表中的货币列为第二个货币。 对于美国的Somoa来说,那将是'US Dollar,Kwanza'
。 以-1
作为参数的下一个调用采用列表的最后一个元素,即'Kwanza'
,这是currencies
的第二个元素。
另请注意,SQL查询返回一组明确定义的列。 查询不能具有可变数量的列(除非您通过prepare
语句使用动态SQL)。
使用此查询计算出您需要的货币列数:
SELECT MAX(c) FROM
((SELECT count(currency.name) AS c
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) as t)
然后动态创建并执行预准备语句以生成结果,使用带有上述查询结果的Gordon Linoff解决方案在此线程中。
Ypu可以使用动态SQL,但您必须使用过程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.