Mysql根据列值加入三个表

时间:2017-02-27 13:43:30

标签: mysql join

我有三张桌子

的USR

ID   Name
--------
1   Mark Dav
2   Dan Fos

CUST

ID   Name
--------
1   Jane Cue
2   Mary Tie

封邮件

ID   Frm_ID  To_ID  Msg    frm_cat to_cat
--------
1     1      1      hello  usr      cus
1     1      2      There  usr      cus
1     2      1      hello  cus      usr
1     2      2      hello  cus      usr

如何加入表格以便获得以下结果。

封邮件

ID   Frm_ID  To_ID   Frm_name To_name   Msg    frm_cat to_cat
------------------------------------------------
1     1      1       Mark Dav Jane Cue  hello  usr      cus
1     1      2       Mark Dav Mary Tie  There  usr      cus
1     2      1       Mark Tie Mark Dav  hello  cus      usr
1     2      2       Mark Tie Dan Fos   hello  cus      usr

我的尝试

id as id,
  m.frm_id,
  m.to_id,
  m.msg,
  f.name frm_name,
  t.name to_name,
from msgs m 
  left join usrs on f.id = m.from_id AND m.from_cat = 'usr' OR cust f on f.id = m.frm_id AND m.from_cat = 'cus'
  left join usrs t on t.id = m.to_id AND m.from_cat = 'usr' OR cust f on f.id = m.fom_id AND m.from_cat = 'cus';

但我收到了一系列错误

1 个答案:

答案 0 :(得分:0)

您可以使用union all子查询将usrscust堆叠在一起,然后使用from_catto_cat字段来决定要加入的值。不幸的是,MySQL不支持CTE,所以除非你想为此创建一个视图,否则你可以使用相同的union all查询两次,每次连接一次:

SELECT m.id, frm_id, to_id, msg, frm_name, to_name, frm_cat, to_cat
FROM   msgs m
JOIN   (SELECT id, name AS frm_name, 'usr' AS cat
        FROM   usrs
        UNION ALL 
        SELECT id, name AS frm_name, 'cus' AS cat
        FROM   cust) f ON m.frm_id = f.id AND f.frm_cat = f.cat
JOIN   (SELECT id, name AS to_name, 'usr' AS cat
        FROM   usrs
        UNION ALL 
        SELECT id, name AS to_name, 'cus' AS cat
        FROM   cust) f ON m.to_id = f.id AND t.to_cat = f.cat