统一元组

问题描述 投票:1回答:2

我希望我记得SQL,这不是一个愚蠢的问题......:我将复杂查询的结果作为包含两个元素的元组,我想获得一个包含这些元素的联合的列表。我正在使用Postgresql,但我喜欢标准的SQL

所以,我选择foo作为结果

(field_1_1, field_1_2),
(field_2_1, field_2_2),
...

而且我要

(field_1_1),
(field_1_2),
(field_2_1),
(field_2_2)

我能怎么做?

sql postgresql
2个回答
1
投票

你可以使用unnest():

with my_table (col1, col2) as (
values
    ('f11', 'f12'),
    ('f21', 'f22')
)

select unnest(array[col1, col2])
from my_table;

 unnest 
--------
 f11
 f12
 f21
 f22
(4 rows)

或联盟:

select col1
from my_table
union all
select col2
from my_table;

请注意,没有ORDER BY子句,结果行的顺序是不确定的。


0
投票

我使用TRIM()函数只是为了从第二个元素中删除前导空格。

此作业没有标准的SQL方法,每个DMBS都有特定的功能。

create table tbl (foo text);
insert into tbl values
('field_1_1, field_1_2'),
('field_2_1, field_2_2');
✓

2 rows affected
select trim(from split_part(foo, ',', 1)) from tbl
union 
select trim(from split_part(foo, ',', 2)) from tbl;
| btrim     |
| :-------- |
| field_1_1 |
| field_1_2 |
| field_2_1 |
| field_2_2 |
select trim(from unnest(string_to_array(foo, ',')))
from   tbl;
| btrim     |
| :-------- |
| field_1_1 |
| field_1_2 |
| field_2_1 |
| field_2_2 |

dbfiddle here

© www.soinside.com 2019 - 2024. All rights reserved.