|
我搜索了很多,但是没有找到合适的方法来解决我的问题。
$ Z3 D. F ~8 f1 `7 h7 ~我要怎么办* H- e% n6 P0 T# ?% W1 f
我在MySQL有两种表格:-国家-货币(因为多对多的关系,我通过了CountryCurrency把它们连接起来->)8 G3 N( T) y6 r6 }0 P; j
见以下示例:http :
) O2 G+ U* t6 v//sqlfiddle.com/#!2/317d3/8/0* b" {: l& B) t
我想用联系把两个表链接在一起,但我认为每个国家/地区只显示一行(有些国家/地区使用各种货币,所以这是第一个问题)。
! [+ Z2 w. D9 _- k% x我找到了group_concat函数:
Q; m# M, y4 o P$ i6 MSELECT country.Name,country.ISOCode_2,group_concat(currency.name) AS currencyFROM countryINNER JOIN countryCurrency ON country.country_id = countryCurrency.country_idINNER JOIN currency ON currency.currency_id = countryCurrency.currency_idGROUP BY country.name结果如下:& d) L/ z# k9 k1 Z
NAME ISOCODE_2 CURRENCYAfghanistan AF Afghani脜land Islands AX EuroAlbania AL LekAlgeria DZ Algerian DinarAmerican Samoa AS US Dollar,Kwanza,East Caribbean Dollar但我现在想把货币分成不同的列(货币1,货币2,…)。我试过MAKE_SET()等功能,但这不起作用。
' M: Z* {! k A$ o% [- F% P# m
8 Y! F" X2 ^0 G! R4 H; P 解决方案: 0 f2 q# w/ ?6 o+ e) {+ i( z$ h6 V
您可以使用substring_index()。以下查询将您的查询作为子查询,然后应用此逻辑:/ r2 u# ]# X& L$ r/ _" D# O1 _
select Name,ISOCode_二、 substring_index(currencies,,1) as Currency (case when numc >= 2 then substring_index(substring_index(currencies,,-1) end) as Currency二、 (case when numc >= 3 then substring_index(substring_index(currencies,,-1) end) as Currency3、 (case when numc >= 4 then substring_index(substring_index(currencies,,-1) end) as Currency4, (case when numc >= 5 then substring_index(substring_index(currencies,,-1) end) as Currency5、 (case when numc >= 6 then substring_index(substring_index(currencies,,-1) end) as Currency6、 (case when numc >= 7 then substring_index(substring_index(currencies,,-1) end) as Currency7, (case when numc >= 8 then substring_index(substring_index(currencies,,-1) end) as Currency8from (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)使用货币列表,直到第二种货币。对于美属索莫亚来说,那就是USDollar,Kwanza'。使用-当参数作为下一个调用时,使用列表的最后一个元素,即Kwanza这是第二个元素currencies。2 G$ j2 D7 h* I5 @ @- G! x0 D
还要注意,SQL查询返回一组定义明确的列。除非您通过,否则查询不能有可变列数(prepare动态语句SQL )。 |
|