我正在尝试从包含国家/地区代码数据的3个不同列的表中选择不同国家/地区代码的列表。
示例
Raw Desired
+-----------+-----------+-----------+ +-----------+
| country_1 | country_2 | country_3 | | countries |
+-----------+-----------+-----------+ +-----------+
| GBR | GBR | IRL | | ARG |
| DEU | FRA | CHE | | AUS |
| CHN | CHN | IND | | BRA |
| USA | CAN | MEX | | CAN |
| AUS | JAP | KOR | | CHE |
| BRA | ARG | ARG | | CHN |
| NOR | SWE | FIN | | DEU |
| GBR | FRA | GBR | | FIN |
| IRL | IRL | IRL | | FRA |
+-----------+-----------+-----------+ | GBR |
| IND |
| IRL |
| JAP |
| KOR |
| MEX |
| NOR |
| SWE |
| USA |
+-----------+
我到目前为止最接近的是查询:
mysql> SELECT
CONCAT(
(SELECT GROUP_CONCAT(DISTINCT country_1 ORDER BY country_1) FROM tbl),
',',
(SELECT GROUP_CONCAT(DISTINCT country_2 ORDER BY country_2) FROM tbl),
',',
(SELECT GROUP_CONCAT(DISTINCT country_3 ORDER BY country_3) FROM tbl)
) AS countries;
+-------------------------------------------------------------------------------------------------+
| countries |
+-------------------------------------------------------------------------------------------------+
| AUS,BRA,CHN,DEU,GBR,IRL,NOR,USA,ARG,CAN,CHN,FRA,GBR,IRL,JAP,SWE,ARG,CHE,FIN,GBR,IND,IRL,KOR,MEX |
+-------------------------------------------------------------------------------------------------+
但正如你所看到的,仍然有重复,我不知道如何将它们排成行。
感谢任何帮助!
答案 0 :(得分:2)
我不确定你为什么要使用群组连结。使用union可以轻松完成所需的结果,自动删除重复项。
SELECT country1 AS countries FROM tab
UNION
SELECT country2 FROM tab
UNION
SELECT country3 FROM tab
ORDER BY 1;
答案 1 :(得分:1)
您得到重复项,因为您只在每列中消除重复项,而不是整体。你可能想要更像这样的东西:
SELECT GROUP_CONCAT(country)
FROM (
SELECT DISTINCT country1 AS country FROM tbl
UNION
SELECT DISTINCT country2 AS country FROM tbl
UNION
SELECT DISTINCT country3 AS country FROM tbl
)