解决in效率问题

解决in效率问题

1. regexp_split_to_table

将数组转变成一张单字段临时表

1
2
3
4
5
6
7
8
-- 获取数组
select array_agg(code) from dy_fin_account_period;

-- 数组转字符串
select array_to_string(array_agg(code),',') from dy_fin_account_period

-- 数组转表(注意:array_to_string(array_agg(code),',') 可以替换成逗号隔开的字符串,注意字符串中间不能出现【空格】)
select regexp_split_to_table(array_to_string(array_agg(code),','),',') as p_code from dy_fin_account_period

2. exists

1
2
3
4
5
select * from hr_employee where user_id not in (select id from res_users where id > 10);

select * from hr_employee where exists (select 1 from res_users ru where ru.id > 10 and ru.id != hr_employee.user_id);

select * from hr_employee where not exists (select 1 from res_users ru where ru.id > 10 and ru.id = hr_employee.user_id);

3. 注意

=比<>快,如果出现<>,可以调整成not exists与=

4. 快速将字符串转成多列表

1
2
3
4
5
SELECT split_part(t.item, ',', 1) AS state,
split_part(t.item, ',', 2) AS process_value
FROM (
SELECT unnest(string_to_array('value0,0-value1,0-value2,0.05-value3,0.25-value6,0.5-value8,0.75-value9,0.9-value10,1-value11,0','-')) AS item
) AS t;