Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 使用或在多个列上通过左连接创建视图_Mysql_Sql_Join_View_Left Join - Fatal编程技术网

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

Mysql 使用或在多个列上通过左连接创建视图,mysql,sql,join,view,left-join,Mysql,Sql,Join,View,Left Join,我试图通过左键连接两列,从两个表中创建一个视图:t1.recipient\u email=t2.username或t1.created\u by=t2.id。如下面的伪代码所示,我希望第一个t2.name是收件人的名称,第二个t2.name是发件人的名称。我想不出实现这一目标的正确方法 CREATE VIEW emailsent_log_view (id_email_que_log, date_sent, recipent_email, recipient_name, send_status,

我试图通过左键连接两列,从两个表中创建一个视图:
t1.recipient\u email=t2.username
t1.created\u 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

正如您所猜测的,您无法选择哪一行使用
或类似的
条件连接到哪一行。解决此类问题的方法是两次加入表,每次需要一次:

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

你为什么想要一个视图呢?我想要一个视图,这样应用程序(如“杂货店crud”)从一个视图而不是多个表中获取数据就更容易了。我怀疑应用程序通常会发现这两种方法都同样简单。在我看来,MySQL中的视图几乎没有任何用处。谢谢@Mureinik。您的解决方案正是我想要的。请注意,任何访问此视图的应用程序都无法区分res.name和snd。name@Strawberry说得好。编辑文章以添加别名并使其可区分