[英]Select minimum time for the same id from two tables (MySQL)
Hi I have two tables and for the same contact "email" in the two tables, I want to know the first time the "email" gets in touch. 嗨,我有两个表,并且对于两个表中的同一联系人“电子邮件”,我想知道“电子邮件”的第一次联系。
conversation_and_id conversation_and_id
contact 联系
So far I only have done outer join to join the two tables, but it removed duplicated "email", which I need it to compare time difference from the same "email". 到目前为止,我只做过外部联接来联接两个表,但是它删除了重复的“电子邮件”,我需要它来比较同一“电子邮件”的时差。
ALTER TABLE conversation_and_id CHANGE `email` `conversation_and_id_email` VARCHAR(100);
create table conversation_and_id_and_contact
SELECT *
FROM contact AS con
LEFT JOIN conversation_and_id AS ci ON con.email = ci.conversation_and_id_email
UNION
SELECT *
FROM contact AS con
RIGHT JOIN conversation_and_id AS ci ON con.email = ci.conversation_and_id_email;
create table final
select
if (f.email is not null, f.email, f.conversation_and_id_email) as email1,
if (f.atlas_interest is not null, f.atlas_interest, f.created_at) as time1,
if (f.conversation_and_id_email is not null, f.conversation_and_id_email, f.email) as email2,
if (f.created_at is not null, f.created_at, f.atlas_interest) as time2
from conversation_and_id_and_contact f;
The standard solution everywhere is to perform a full outer join with both tables and get the MIN()
timestamp. 各处的标准解决方案是对两个表执行完全外部联接并获得
MIN()
时间戳。
However, since MySQL does not (yet) support full outer joins you'll need to union a left and right joins to get the result you want. 但是,由于MySQL还不支持完全外部联接,因此您需要对左右联接进行联合以获得所需的结果。 The final [unnecessarily long] query looks like:
最终的[不必要的长]查询如下所示:
select
coalesce(iemail, cemail) as email,
least(created_at, atlas_interest) as expressed_interest_at
from (
select -- this is the left join
i.email as iemail, i.created_at, c.email as cemail, c.atlas_interest
from conversation_and_id i
left join contact c on c.email = i.email
union
select -- this is the right join
i.email as iemail, i.created_at, c.email as cemail, c.atlas_interest
from conversation_and_id i
right join contact c on c.email = i.email
) x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.