使用或在多个列上通过左连接创建视图

gcuhipw9  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(297)

我正试图通过在两列上左键联接,从两个表中创建一个视图: t1.recipient_email = t2.username 或者 t1.created_by = t2.id . 如下面的伪代码所示,我希望第一个t2.name是收件人的名称,第二个t2.name是发件人的名称。我想不出实现这一目标的正确方法。

CREATE VIEW  emailsent_log_view
(id_email_que_log, date_sent, recipent_email, recipient_name, send_status, sender_name)
 AS
SELECT
    t1.id,
    t1.date_send,
    t1.recipient_email,
    t2.name, --recipient_name: corresponds with t1.recipient_email = t2.username
    t1.send_status,
    t2.name --sender_name: correspond with t1.created_by = t2.id

    FROM email_que_log AS t1
    LEFT JOIN user_account as t2
    ON  t1.recipient_email = t2.username
    OR t1.created_by = t2.id
zdwk9cvp

zdwk9cvp1#

正如您所猜测的,您无法选择哪一行与具有 or 这样的状况。解决此类问题的方法是两次加入表,每次一次:

CREATE VIEW  emailsent_log_view
(id_email_que_log, date_sent, recipent_email, recipient_name, send_status, sender_name)
AS
SELECT
    eql.id,
    eql.date_send,
    eql.recipient_email,
    res.name AS reciever, -- From the first join
    eql.send_status,
    snd.name AS sender -- From the second join
FROM
    email_que_log AS eql
LEFT JOIN 
    user_account AS res ON eql.recipient_email = res.username
LEFT JOIN 
    user_account AS snd ON eql.created_by = snd.id

相关问题