【问题标题】:Re-mapping rows in MYSQL在 MYSQL 中重新映射行
【发布时间】:2018-05-14 10:04:48
【问题描述】:

我有这样的表:

uid |确定 |价值 1 | 1 | nameOf1 1 | 2 |姓氏Of1 1 | 3 |国家/地区 2 | 1 | nameOf2 2 | 2 |姓Of2

并且需要像这样转换/选择它:

uid |姓名 |姓氏 |国家 1 | nameOf1 |姓氏Of1 |国家/地区 2 | nameOf2 |姓Of2 | ..

【问题讨论】:

标签: mysql remap


【解决方案1】:

尝试类似:

SELECT t1.uid, t2.value AS name, t3.value AS surname, t4.value AS country FROM table t1
  LEFT JOIN table t2 on t2.uid = t1.uid AND t2.fid = 1
  LEFT JOIN table t3 on t3.uid = t1.uid AND t3.fid = 2
  LEFT JOIN table t4 on t4.uid = t1.uid AND t4.fid = 3
  GROUP BY t1.uid;

或:

SELECT DISTINCT t1.uid, t2.value AS name, t3.value AS surname, t4.value AS country FROM table t1
  LEFT JOIN table t2 on t2.uid = t1.uid AND t2.fid = 1
  LEFT JOIN table t3 on t3.uid = t1.uid AND t3.fid = 2
  LEFT JOIN table t4 on t4.uid = t1.uid AND t4.fid = 3;

【讨论】:

  • 我对 280,000 条记录进行了测试(20% 的国家/地区为空)。没有索引,两个查询都太慢了。他们几乎不工作。然后我在两列上创建了一个主索引:uid 和 fid。并且这两个查询或多或少都运行得很快。
【解决方案2】:

这有点复杂,但你可以这样做:

select distinct uid as uid,
   (select value from dataTable as table1 
           where table1.uid=dataTable.uid and fid = 1) as name,
   (select value from dataTable as table2 
           where table2.uid=dataTable.uid and fid = 2) as surname,
   (select value from dataTable as table3 
           where table3.uid=dataTable.uid and fid = 3) as country
from dataTable group by uid

SQLFiddle

【讨论】:

    猜你喜欢
    • 2012-01-06
    • 2013-01-15
    • 2018-10-12
    • 2013-10-14
    • 2014-12-30
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 2013-11-29
    相关资源
    最近更新 更多