【问题标题】:How to create multiple rows from a initial row如何从初始行创建多行
【发布时间】:2017-01-13 04:52:25
【问题描述】:

我用的是mysql db engine,我想知道有没有可能将表中的一行数据转移到另一个表中,这个表由两列组成,id和value 每个传输的值都将进入一行,并且行看起来像 ID,值,并且只要它具有传输到新行的值,只要它具有属于的 id 的值,就维护 id从中转移的行

初始表的样子

id  |country_name   |city_1      |city_2      |city_3      |city_4
------------------------------------------------------------------------
1   |Some_country   |some_city1  |some_city2  |some_city3  |some_city4

想要的桌子看起来像

 id | city_name
 1  |  some_city1
 1  |  some_city2
 1  |  some_city3
 1  |  some_city4

【问题讨论】:

  • @chambo 它不是重复的,因为这是 MS SQL 的解决方案,而 MySQL 没有 unpivot 功能
  • 我很抱歉 - 我没有注意到标签。但是它仍然是重复的:stackoverflow.com/questions/15184381/…

标签: mysql sql


【解决方案1】:

将此用于特定的ID

select id, city_name from(
    select id, city_1 as city_name from yourTable    
    union all
    select id, city_2 from yourTable    
    union all
    select id, city_3 from yourTable    
    union all
    select id, city_4 from yourTable
) as t where id= yourID

http://sqlfiddle.com/#!9/7ee1f/1

整个表都用这个

 select id, city_name from(
    select id, city_1 as city_name from yourTable    
    union all
    select id, city_2 from yourTable    
    union all
    select id, city_3 from yourTable    
    union all
    select id, city_4 from yourTable
) as t
order by id

【讨论】:

  • 你可能应该在上面扔一个 ORDER BY id。我假设 OP 希望在继续 id 2 之前查看 id 1 的所有城市
  • @Horaciux 我只插入了一行sql,我说,INSERT INTO myTable(id,city_name) 运行顺利,非常感谢!
  • @Horaciux 我的错误,这不是完全正确的答案,因为如果你说哪里 id = 1,它工作正常,但如果你说哪里 id = id,因为我想这样做整个表,它只返回city_1,但行有city_1,city_2 ...
  • @MPetrovic 删除where 子句
  • @Horaciux 很抱歉打扰你,谢谢,这是正确的,我完全预测到了这一点
【解决方案2】:

您要查找的内容通常称为垂直旋转:您希望将诸如四个城市名称的数组(硬连线到表定义中)旋转成四个垂直行。

解决方案是与一个临时表进行交叉连接,该表具有从 1 开始的多个连续整数,因为您有要旋转的列,并​​结合使用该系列整数的 CASE-WHEN 表达式。

看这里:

WITH foo(id,country_name,city_1,city_2,city_3,city_4) AS (
SELECT 1,'Some_country','some_city1','some_city2','some_city3','some_city4'
)
,    four_indexes(idx) AS (
          SELECT 1
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4
)
SELECT
  id  AS country_id
, idx AS city_id
, CASE idx 
    WHEN 1 THEN city_1
    WHEN 2 THEN city_2
    WHEN 3 THEN city_3
    WHEN 4 THEN city_4
    ELSE ''
  END AS city_name
FROM foo CROSS JOIN four_indexes
;
country_id|city_id|city_name
         1|      1|some_city1
         1|      3|some_city3
         1|      2|some_city2
         1|      4|some_city4

就在前几天,我回答了一个问题,该问题正在寻找反转我们在这里执行的操作:水平旋转。 如果你好奇,请看这里... How to go about a column with different values in a same row in sql?

玩得开心-

理智的马可

【讨论】:

  • 非常感谢您的努力,@Horaciux 的回答解决了我的问题,而且,当我解决了什么是什么时,我想测试您的回答,因为这对我来说有点困惑,因为没看懂,我尽量理解,谢谢
  • 你在纠结什么?交叉连接? WITH子句? CASE 表达式?以上都是?
猜你喜欢
  • 2023-02-02
  • 1970-01-01
  • 1970-01-01
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 2014-09-04
相关资源
最近更新 更多