可以将以下查询合并到一个查询中吗?
1
public function create($station_id)
2
select a.usr_id, a.usr_desc as ,a.usr_type,b.usr_desc as usr_prof_name
from sc_usr_prof_m a, sc_usr_type_m b
where a.usr_type=b.usr_type
and a.current_status='A'
order by a.usr_id;
3
select distinct a.usr_id,a.usr_desc,b.dept_name
from sc_usr_prof_m a ,sc_user_depts b
where a.usr_id=b.usr_id
and a.usr_status='E'
and a.current_status='A';
4
select a.usr_id,a.usr_desc,b.curr_code,b.min_amt,b.max_amt
from sc_usr_prof_m a, sc_auth_limit_m b
where a.usr_id=b.usr_id
and a.usr_status='E'
and a.current_status='A'
and b.max_amt not in ('0')
order by b.usr_id;
答案 0 :(得分:0)
在不知道你的桌子结构的情况下,很难准确地说出哪种方式能给你带来最好的结果。你可以将查询重写为一个,将各个表连接在一起,但似乎有很多不同的表选择。如果不知道你的桌子设计,就很难说这是否是最好的行动方案。
或者,如果您只是想将结果集合并到一个数据集中,基本上将每个查询的结果合并为一个输出,那么您可以使用UNION [ALL]
。您需要确保每个查询的选择列表中的列正确匹配/对齐。这不是理想的,但应该给你你想要的东西。
with combined_results as (
select a.usr_id as usr_id,
a.usr_desc as usr_desc,
a.usr_type as usr_type,
b.usr_desc as usr_prof_name,
null as dept_name,
null as cur_code,
0 as min_amt,
0 as max_amt,
null as msg_type
from sc_usr_prof_m a, sc_usr_type_m b
where a.usr_type=b.usr_type
and a.current_status='A'
union all
select distinct
a.usr_id as usr_id,
a.usr_desc as usr_desc,
null as usr_type,
null as usr_prof_name,
b.dept_name as dept_name,
null as cur_code,
0 as min_amt,
0 as max_amt,
null as msg_type
from sc_usr_prof_m a ,sc_user_depts b
where a.usr_id=b.usr_id
and a.usr_status='E'
and a.current_status='A'
union all
select a.usr_id as usr_id,
a.usr_desc as usr_desc,
null as usr_type,
null as usr_prof_name,
null as dept_name,
b.curr_code as curr_code,
b.min_amt as min_amt,
b.max_amt as max_amt,
null as msg_type
from sc_usr_prof_m a, sc_auth_limit_m b
where a.usr_id=b.usr_id
and a.usr_status='E'
and a.current_status='A'
and b.max_amt not in ('0')
union all
select a.usr_id as usr_id,
a.usr_desc as usr_desc,
null as usr_type,
null as usr_prof_name,
null as dept_name,
null as cur_code,
0 as min_amt,
0 as max_amt,
b.msg_type as msg_type
from sc_usr_prof_m a, sc_user_msgs_m b
where a.usr_id=b.usr_id
and a.usr_status='E'
and a.current_status='A'
and b.swift_enable='Y'
)
select *
from combined_results
order by usr_id;
我还建议你写出你的联接:
select a.col1, a.col2, b.col3, b.col4
from my_a_table a
join my_b_table b
on b.col1 = a.col1
where a.col1 = 123;
而不是您目前的表现如何:
select a.col1, a.col2, b.col3, b.col4
from my_a_table a, my_b_table b
where b.col1 = a.col1
and a.col1 = 123;
如果没有其他原因而不是可读性,尤其是在具有多个连接的较大查询中。