我有两张table,分别是department和function。
部门
------------------------
dept_id | dept_name
------------------------
1 | department1
2 | department2
------------------------
功能
--------------------------------------------------------------
function_id | function_name | dept_id | is_main_function
--------------------------------------------------------------
1 | function1 | 1 | 1
2 | function2 | 1 | 0
3 | function3 | 1 | 0
--------------------------------------------------------------
这是我的问题
select dept_name,function_name as main_function,null as sub_function from department d,functon f where d.dept_id = f.dept_id and is_main_function = 1
union
select dept_name,null as main_function,function_name as sub_function from department d,functon f where d.dept_id = f.dept_id and is_main_function = 0
此查询的输出为
------------------------------------------------
dept_name | main_function | sub_function
------------------------------------------------
department1 | function1 | null
department1 | null | function2
department1 | null | function2
------------------------------------------------
但我想要的是
------------------------------------------------
dept_name | main_function | sub_function
------------------------------------------------
department1 | function1 | function2
department1 | function1 | function2
------------------------------------------------
有可能得到这个输出吗?
2条答案
按热度按时间wlwcrazw1#
试试这个,它用
JOIN
要实现您的目标:ercv8c1e2#
您可以使用以下解决方案
INNER JOIN
而不是UNION
:demo:https://www.db-fiddle.com/f/owqzs9c1bngf4zwcswtirf/1