将 table 字段中的单词拆分为新行

Split Word in table field into new row

我有这样的 postgres table select name from product

左边是现在查询的结果,右边是应该的结果

我怎样才能做到?谢谢

您可以使用 split_part 函数和 union 来实现您想要的结果,如下所示。

select * from (
SELECT split_part(c1, ' ', 1) as Name from t1
union all
SELECT split_part(c1, ' ', 2) from t1
) t
where t.Name <> ''
order by 1;

外部查询用于过滤掉是否有任何空字符串输出,例如在 paint.

的情况下

结果:

name
----------
adobe
chrome
google
microsoft
office
paint
reader
studio
virtual

你可以查看演示 here

您可以使用regexp_split_to_table来拆分单词。假设您的 table 名称是 "product" 并且列是 "name",这里是 sql:

SELECT regexp_split_to_table(name, E'\s+') as name FROM product;

完整测试SQL,结果附在下面:

create table product(
    name varchar(200)
    );
insert into product values('microsoft office');
insert into product values('virtual studio');
insert into product values('adobe reader');
insert into product values('adobe photoshop 9');
insert into product values('paint');
insert into product values('google chrome');

SELECT regexp_split_to_table(name, E'\s+') as name FROM product;

结果:

    name
1   microsoft
2   office
3   virtual
4   studio
5   adobe
6   reader
7   adobe
8   photoshop
9   9
10  paint
11  google
12  chrome