【问题标题】:Create View by Left join on multiple columns with OR使用 OR 在多个列上通过左连接创建视图
【发布时间】:2019-02-19 16:09:54
【问题描述】:

我正在尝试通过左连接两列来从两个表创建视图:t1.recipient_email = t2.usernamet1.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

【问题讨论】:

  • 你为什么想要一个视图?
  • 我想要一个视图,这样“Grocery crud”之类的应用程序可以更轻松地从单个视图而不是多个表中获取数据
  • 我怀疑应用程序通常会发现这两种方法同样简单。在我看来,MySQL 中的视图几乎没有任何用处

标签: mysql sql join view left-join


【解决方案1】:

正如您所猜想的,您无法选择哪一行连接到具有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

【讨论】:

  • 谢谢@Mureinik。您的解决方案正是我想要的。
  • 请注意,任何访问此视图的应用程序都无法区分 res.name 和 snd.name
  • @Strawberry 好点。编辑帖子以添加别名并使其可区分
猜你喜欢
  • 2019-06-23
  • 1970-01-01
  • 2015-11-09
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-11
  • 1970-01-01
相关资源
最近更新 更多