[英]Row to column transformation from different tables and different rows number (union) in MySQL version 8.0.17 using Pivot
[英]Transform rows into a single column in MySQL (8.0.17)
我试图搜索帖子,也没有任何结果,也许我没有使用正确的词。
我需要 MySQL (8.0.17) 中的解决方案。
我有一个包含 4 列的表(称为country
):
1. Code
2. Name
3. Continent
4. Region
这些是行
+------+-------------+---------------+---------------------------+
| Code | Name | Continent | Region |
+------+-------------+---------------+---------------------------+
| ABW | Aruba | North America | Caribbean |
| AFG | Afghanistan | Asia | Southern and Central Asia |
| AGO | Angola | Africa | Central Africa |
| AIA | Anguilla | North America | Caribbean |
| ALB | Albania | Europe | Southern Europe |
+------+-------------+---------------+---------------------------+
我需要做一个选择它会返回
+----------------------------+
| Contents |
+----------------------------+
| ABW |
| Aruba |
| North America |
| Caribbean |
| AFG |
| Afghanistan |
| Asia |
| Southern and Central Asia |
| AGO |
| Angola |
| Africa |
| Central Africa |
| AIA |
| Anguilla |
| North America |
| Caribbean |
| ALB |
| Albania |
| Europe |
| Southern Europe |
+----------------------------+
此外,我想将一个记录的所有 4 列保留在一起。
DROP TABLE IF EXISTS `country`;
CREATE TABLE `country` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`Code` CHAR(3) NOT NULL,
`Name` CHAR(52) NULL DEFAULT NULL,
`Continent` VARCHAR(50) NULL DEFAULT NULL,
`Region` CHAR(26) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;
-- ----------------------------
-- Records of country
-- ----------------------------
INSERT INTO `country` (`id`, `Code`, `Name`, `Continent`, `Region`) VALUES (1, 'ABW', 'Aruba', 'North America', 'Caribbean');
INSERT INTO `country` (`id`, `Code`, `Name`, `Continent`, `Region`) VALUES (2, 'AFG', 'Afghanistan', 'Asia', 'Southern and Central Asia');
INSERT INTO `country` (`id`, `Code`, `Name`, `Continent`, `Region`) VALUES (3, 'AGO', 'Angola', 'Africa', 'Central Africa');
INSERT INTO `country` (`id`, `Code`, `Name`, `Continent`, `Region`) VALUES (4, 'AIA', 'Anguilla', 'North America', 'Caribbean');
INSERT INTO `country` (`id`, `Code`, `Name`, `Continent`, `Region`) VALUES (5, 'ALB', 'Albania', 'Europe', 'Southern Europe');
您可以使用UNION ALL
来选择所有这些,如果您有一个自动递增的主键id
。
SELECT txt
FROM (SELECT id AS pk, `code` AS txt FROM country
UNION ALL SELECT id, `name` FROM country
UNION ALL SELECT id, Continent FROM country
UNION ALL SELECT id, Region FROM country) AS t
ORDER BY t.pk;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.