【发布时间】:2016-09-26 16:01:46
【问题描述】:
我有一个表 email_activities_2,有一个标题为“action_type”的列,其中结果可以是“sent”、“open”、“click”等,每个 action、每个 email、每个 recipient_id 都有一条记录.例如,recipient_id 54 的 email_id 94607 有两行:第一行的 action_type 是“已发送”,第二行是“打开”。
我想要一个查询,它将在一行中返回,action_type 列列出了两次,但在左边,只显示 action_type = "sent",而右边的列是 action_type = "open" 或 "null"
这是我最接近我想要的:
select email2.email_id, email2.recipient_id, email2.action_type as sent,
opens.action_type as opened
from email_activities_2 email2
left join email_activities_2 opens on email2.id = opens.id
where email2.action_type = "sent"
union all
select email2.email_id, email2.recipient_id, email2.action_type as sent,
opens.action_type as opened
from email_activities_2 email2
right join email_activities_2 opens on email2.id = opens.id
where opens.action_type = "open"
order by recipient_id, email_id asc;
这会返回:
email_id | recipient_id | sent | opened
94607 54 sent sent
94607 54 open open
94981 54 sent sent
98479 54 sent sent
98479 54 open open
当我想要的是:
email_id | recipient_id | sent | opened
94607 54 sent open
94981 54 sent NULL
98479 54 sent open
这可能吗?我是 SQL 的新手,我正在努力解决这个问题。
【问题讨论】:
-
您想查看“表别名”以创建表的虚拟“副本”,以便可以在查询中使用它两次。如果您有问题,请设置一个小提琴并发布它。
标签: mysql sql mysql-workbench self-join