mysql - 使用联合查询组合 MySql 的 varchar 行

标签 mysql union

我有两个表,分别是 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      
------------------------------------------------

是否可以得到这个输出?

最佳答案

您可以使用以下解决方案使用 INNER JOIN而不是 UNION:

SELECT d.dept_name, f1.function_name AS main_function, f2.function_name AS sub_function
FROM department d 
    INNER JOIN `function` f1 ON d.dept_id = f1.dept_id AND f1.is_main_function = 1 
    INNER JOIN `function` f2 ON d.dept_id = f2.dept_id AND f2.is_main_function = 0 

demo: https://www.db-fiddle.com/f/owQzS9C1bnGF4zwCSWtirF/1

关于mysql - 使用联合查询组合 MySql 的 varchar 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51979628/

相关文章:

mysql - 选择多个表中 EACH 2 个表之间共有的所有值

c++ - flatbuffer unio 只生成枚举

sql-server - 为什么在派生表的存储过程中使用UNION?

php - 如何检查是否在 laravel Eloquent 中插入了一行表?

mysql - 我如何提交我的 Angular 表格?

mysql - 如何在 MySQL 中加入这两个表

php - 如何对 codeigniter 数据库类中的列求和?

php - 从 mysql 中获取列值包含两个字符串的数据

sql - PostgreSQL:如何对未包含列的联合查询进行排序?

excel - 计算 SMA 时处理空白单元格