INSERT OVERWRITE TABLE dw_rpt_report60010105049 SELECT COALESCE(n.char3, dw.tran_country) AS tran_country, dw.col2, dw.col3, ... FROM dw_rpt_report60010105049 dw LEFT JOIN ( SELECT char2, MAX(char3) AS char3 FROM orsuser_kara.para_nationality GROUP BY char2 ) n ON dw.tran_country = n.char2 WHERE n.char2 IS NOT NULL 此段代码中的主表的tran_country不是唯一的,可能会导致发散,怎么优化
时间: 2024-02-18 09:02:29 浏览: 201
可以考虑使用子查询或者临时表的方式,先将主表的tran_country进行去重,再进行JOIN操作。具体实现方式如下:
使用子查询:
```
INSERT OVERWRITE TABLE dw_rpt_report60010105049
SELECT COALESCE(n.char3, t.tran_country) AS tran_country, t.col2, t.col3, ...
FROM (
SELECT DISTINCT tran_country, col2, col3, ...
FROM dw_rpt_report60010105049
) t
LEFT JOIN (
SELECT char2, MAX(char3) AS char3
FROM orsuser_kara.para_nationality
GROUP BY char2
) n ON t.tran_country = n.char2
WHERE n.char2 IS NOT NULL
```
使用临时表:
```
CREATE TEMPORARY TABLE temp_table AS
SELECT DISTINCT tran_country, col2, col3, ...
FROM dw_rpt_report60010105049;
INSERT OVERWRITE TABLE dw_rpt_report60010105049
SELECT COALESCE(n.char3, t.tran_country) AS tran_country, t.col2, t.col3, ...
FROM temp_table t
LEFT JOIN (
SELECT char2, MAX(char3) AS char3
FROM orsuser_kara.para_nationality
GROUP BY char2
) n ON t.tran_country = n.char2
WHERE n.char2 IS NOT NULL;
DROP TEMPORARY TABLE temp_table;
```
无论使用哪种方式,在进行JOIN操作之前,都先对主表进行去重,这样可以避免发散的情况发生,提高查询效率。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)