![](/img/trans.png)
[英]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.