pg数据库表A的 mch,pch,lgp,customs 4列的数据类型是string[],内容例{aa,bb},现创建1个视图,将 表A的数据以笛卡尔积的形式展开,要防止冗余的情况发生,sql语句怎么写?
时间: 2024-10-17 19:10:24 浏览: 43
在PostgreSQL中,如果你想通过笛卡尔积的方式对`mch`, `pch`, `lgp`, 和 `customs` 这四列的`string[]`数据进行处理,并且避免冗余,你可以创建一个视图来实现这种操作。但是,PostgreSQL本身并不直接支持笛卡尔积的操作,通常我们会通过动态查询或者生成临时表格的方式来达到类似的效果。这里假设我们能用临时表格存储笛卡尔组合,可以这样做:
```sql
CREATE TEMP TABLE temp_table AS
SELECT unnest(mch) AS mch,
unnest(pch) AS pch,
unnest(lgp) AS lgp,
unnest(customs) AS customs
FROM tableA;
-- 现在temp_table包含所有可能的四列组合
```
然后,你可以基于这个临时表进行后续的操作,如联接、分组等,而不会产生冗余。
如果你需要得到所有的组合并显示出来,可以再做一个交叉表查询:
```sql
SELECT * FROM temp_table
CROSS JOIN lateral (
SELECT unnest(array[1, 2]) AS id1
CROSS JOIN lateral (
SELECT unnest(array[1, 2]) AS id2
CROSS JOIN lateral (
SELECT unnest(array[1, 2]) AS id3
CROSS JOIN lateral (
SELECT unnest(array[1, 2]) AS id4
FROM generate_series(1, array_length(temp_table.mch, 1)) AS g(id)
) AS t3
) AS t2
) AS t1
) AS t0;
```
这将生成所有可能的4列值组合。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)