mysql - 将列显示为原始数据
问题描述
想象一下下面的表格: 客户:
ID Name Family Child1 Age1 Child2 Age2 Child3 Age3
1 Andy Constant Robbert 2 Elina 5 Sofia 1
2 Doro Panayi Costas 4
我想得到的是低于resault。
Name age ParentName ID
Robert 2 Andy Constantin 1
Elina 5 Andy Constantin 1
Sofia 1 Andy Constantin 1
Costas 4 Doros Panayi 2
我将不胜感激任何帮助
解决方案
对于有限数量的孩子来说并不难(对于更大的家庭来说可能也不那么繁重)
drop table if exists t;
create table t
(ID int, Name varchar(20), Family varchar(20), Child1 varchar(20), Age1 int, Child2 varchar(20), Age2 int,
Child3 varchar(20), Age3 int);
insert into t values
(1 , 'Andy' , 'Constant' , 'Robbert' , 2 , 'Elina' , 5 , 'Sofia' , 1),
(2 , 'Doro' , 'Panayi' , 'Costas' , 4 , null, null,null,null);
select id,name,family, child1,age1 from t where child1 is not null
union all
select id,name,family, child2,age2 from t where child2 is not null
union all
select id,name,family, child3,age3 from t where child3 is not null;
+------+------+----------+---------+------+
| id | name | family | child1 | age1 |
+------+------+----------+---------+------+
| 1 | Andy | Constant | Robbert | 2 |
| 2 | Doro | Panayi | Costas | 4 |
| 1 | Andy | Constant | Elina | 5 |
| 1 | Andy | Constant | Sofia | 1 |
+------+------+----------+---------+------+
4 rows in set (0.00 sec)
我假设如果孩子的名字为空,那么获取年龄是没有意义的..
推荐阅读
- mysql - 不在rails sql数据库中调用表参数
- flutter - 无法从颤振应用程序正确打开 url 方案
- javascript - 在 Node.js 中导出类的正确方法
- c# - 列表返回类型方法仅返回单个项目(列表中的最后一个)C#.net
- css - 当焦点和编辑 TextInput 它打破左边的价值
- android - 后退按钮不适用于 SafeArea 视图
- python - 如何在 seaborn FacetGrid 中自定义自动行标签?如何获得整个图形的单个 xlabel 和 ylable?
- java - 如何使用来自不同包的方法?
- mysql - 在基于外键检索多条记录时,有没有办法优化查询?
- android - GridLayoutManager 垂直填充项目