Mysql查询两个外键到一个主键

时间:2013-02-22 15:34:01

标签: mysql sql

我有两张桌子:history_tickets&用户

表格1:history_ticket

history_id   |  id_klien    | id_staf   | message
  11         |     77       |   NULL    |  text
  12         |    NULL      |    1      |  text
  13         |     77       |   NULL    |  text

表格2:用户

user_id   |  name    | group   
  1       |   john   |  staff  
  77      |   dion   |  member

我想要这样的结果:

history_id   |  message | user_id  |  name   | group
  11         |    text  |   77     |  dion   |  member
  12         |    text  |    1     |  john   |  staf
  13         |    text  |   77     |  dion   |  member

2 个答案:

答案 0 :(得分:2)

您需要JOIN表:

select h.history_id,
  h.message,
  u.user_id,
  u.name,
  u.group
from history_ticket h
left join users u
  on h.id_staf = u.user_id
  or h.id_klien = u.user_id

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

SELECT  a.HISTORY_ID,
        a.MESSAGE,
        COALESCE(a.ID_KLIEN, a.ID_STAF) UserID,
        COALESCE(b.name, c.name) name,
        COALESCE(b.group, c.group) `group`
FROM    history_ticket a
        LEFT JOIN users b
            ON a.id_klien = b.user_ID
        LEFT JOIN users c
            ON a.id_staf = c.user_ID