例如,我使用的是world.sql数据库,这是一个简短的示例:
CountryCode:char(3) Language:char(30) IsOfficial:enum('T', 'F') Percentage:float(4,1)
每个国家/地区代码都有几个条目,如下所示:
ABW Dutch T 5.3
ABW English T 9.5
我的目标如下:我想获得CountryCode的所有官方语言。即,如果这是ABW的所有国家代码,我希望它返回:
ABW Dutch|English
这是我的MySQL查询:
SELECT
CountryCode,
group_concat(top.offlanguages SEPARATOR "|") AS "Official Languages"
FROM (
SELECT
CountryCode,
Language AS offlanguages
FROM CountryLanguage
WHERE IsOfficial = 'T'
GROUP BY CountryCode
) top
由于某种原因,它返回ABW CountryCode下的每一种可能的语言,我无法弄清楚原因。
即,它返回如下内容:
ABW Dutch | English | Arabic | ...(on and on and on)
答案 0 :(得分:3)
请尝试以下查询
SELECT CountryCode, group_concat(Language separator "|") as "Official Languages"
FROM CountryLanguage where IsOfficial = 'T' group by CountryCode
答案 1 :(得分:1)
您的GROUP BY
位置错误。它应该在top
之后
试试这个:
select CountryCode, group_concat(top.offlanguages separator "|") as "Official Languages" from (
select CountryCode, Language as offlanguages
from CountryLanguage where IsOfficial = 'T'
) top group by CountryCode