Full Outer在MySQL中加入三个表

时间:2017-02-19 11:18:29

标签: mysql sql

我有以下表格和所需的输出。我尝试了基于值和按主题分组的完全加入,但它仍未显示所需的输出

非常感谢任何帮助或指导。以下是MySql查询:

select t1.*,t2.value from Table1 as t1 left join Table2 as t2
on RIGHT(t2.value,1) =RIGHT(t1.value,1) 

union all 
select t1.*,t2.value from Table1 as t1 right join Table2 as t2
on RIGHT(t2.value,1) =RIGHT(t1.value,1)

DDL:

CREATE TABLE Table1 (`subject` varchar(30), `value` varchar(30));
CREATE TABLE Table2 (`subject` varchar(30), `value` varchar(30));
CREATE TABLE Table3 (`subject` varchar(30), `value` varchar(30));

INSERT INTO Table1
(`subject`, `value`)
VALUES
('subject1', 'ValueA1'),
('subject1', 'ValueA2'),
('subject1', 'ValueA3'),
('subject2', 'ValueA4'),
('subject2', 'ValueA5'),
('subject3', 'ValueA6'),
('subject3', 'ValueA7');

INSERT INTO Table2
(`subject`, `value`)
VALUES
('subject1', 'ValueB1'),
('subject1', 'ValueB2'),
('subject2', 'ValueB3'),
('subject1', 'ValueB4'),
('subject2', 'ValueB5'),
('subject3', 'ValueB6');

INSERT INTO Table3
(`subject`, `value`)
VALUES
('subject1', 'ValueC1'),
('subject2', 'ValueC2'),
('subject2', 'ValueC3'),
('subject2', 'ValueC4'),
('subject2', 'ValueC5'),
('subject3', 'ValueC6');

2 个答案:

答案 0 :(得分:2)

您需要将 body = req.getReader().lines().collect(Collectors.joining(System.lineSeparator())); NOT EXISTS一起使用。

我认为有三个表有点复杂,但在这里:

UNION ALL

Demo

答案 1 :(得分:0)

我认为在MySQL中模拟full join的最佳方法是首先选择所有键值,然后使用left join。但是,您不是在寻找full join。这将为每个主题产生笛卡尔积。

你想"列出"每列中的每个主题独立。为此,您可以使用union allgroup by和变量:

select subject,
       max(value1) as value1,
       max(value2) as value2,
       max(value3) as value3
from ((select t1.subject, t1.value as value1, NULL as value2, NULL as value3
              (@rn1 := if(@s1 = subject, @rn1 + 1,
                          if(@s1 := subject, 1, 1)
                         )
              ) as rn
       from table1 t1 cross join
            (select @rn1 := 0, @s1 := '') params
      ) union all
      (select t2.subject, NULL, t2.value, NULL as value3
              (@rn2 := if(@s2 = subject, @rn2 + 1,
                          if(@s2 := subject, 1, 1)
                         )
              ) as rn
       from table2 t2 cross join
            (select @rn2 := 0, @s2 := '') params
      ) union all
      (select t3.subject, NULL as value1, NULL as value2, t3.value as value3
              (@rn3 := if(@s3 = subject, @rn3 + 1,
                          if(@s3 := subject, 1, 1)
                         )
              ) as rn
       from table3 t3 cross join
            (select @rn3 := 0, @s3 := '') params
      )
     )
group by subject, rn;