将LEFT JOIN分成几列

时间:2018-08-21 08:49:15

标签: mysql sql

我有一些表未连接。但是,有一个名为Form的表,我不确定如何将该表与Table User组合。

假定存在三种名为form1,form2和form3的形式。我想为每个电子邮件用户获取每个表单的最新状态。

p.s。由于某些原因,表单记录行会保留并插入新行,而不仅仅是在取消操作后更新表单状态。

我必须全部使用union吗?

表格用户

id    |  email
----------------------------
1     | testing1@testing.com
2     | testing2@testing.com
3     | testing3@testing.com

表格表格

email                    |  form  |  form_status | date
----------------------------------------------------------------------
testing1@testing.com     |  form1 |  completed   | 2018-08-01 12:00:00
testing1@testing.com     |  form2 |  cancelled   | 2018-08-02 12:00:00
testing1@testing.com     |  form2 |  completed   | 2018-08-03 12:00:00
testing1@testing.com     |  form3 |  cancelled   | 2018-08-04 12:00:00
testing2@testing.com     |  form1 |  cancelled   | 2018-08-05 12:00:00
testing2@testing.com     |  form2 |  completed   | 2018-08-06 12:00:00

我的目标是取得以下结果

id    |  email               | form1     | form2     | form3
-----------------------------------------------------------------
1     | testing1@testing.com | completed | completed | cancelled
2     | testing2@testing.com | cancelled | completed | null
3     | testing3@testing.com | null      | null      | null 

我尝试过类似的操作,但是会出错。

SELECT u.id, q.form_status as form1, u.email, 
u.last_successful_login as 'last login in', 
x.c1 as 'xc1', z.c2 as 'zc2' 
FROM user u 
left join yyyy x on u.email = x.email 
left join zzzz z on u.email = z.email 
UNION (
    SELECT
      form_status
    FROM Form f
    WHERE f.email = u.email and f.formtype = 'form1'
  ) q
ORDER BY u.id;

1 个答案:

答案 0 :(得分:1)

您需要使用子查询进行条件聚合:

select u.id, u.email, 
       max(case when f.form = 'form1' then f.form_status end) form1,
       max(case when f.form = 'form2' then f.form_status end) form2,
       max(case when f.form = 'form3' then f.form_status end) form3
from users u left join
     form f
     on f.email = u.email and 
        f.date = (select max(f1.date)
                  from form f1
                  where f1.email = f.email and f1.form = f.form
                 )
group by u.id, u.email;