GROUPBY—如何基于每列为新行创建sql查询?

2ledvvac  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(308)

我有一个sql表,如下所示:

name, email 1, email 2, email 3
John, john@example.com, info@example.com, hello@example.com
Mickey, mickey@disney.com, info@disney.com

我想创建一个查询,为每封电子邮件创建一行。
所以输出看起来像:

John, john@example.com
John, info@example.com
John, hello@example.com
Mickey, mickey@disney.com
Mickey, info@disney.com

我怎样才能做到这一点?

ddrv8njm

ddrv8njm1#

独立于数据库的解决方案使用 union all :

select name, email1 as email
from table1
where email1 is not null
union all
select name, email2 as email
from table1
where email2 is not null
union all
select name, email3 as email
from table1
where email3 is not null;

这需要扫描表三次,所以这不是最有效的解决方案。但是,对于小型或中型table来说,这是很好的。最好的解决方案取决于您使用的特定数据库——如果性能有问题的话。

相关问题