mysql连接表与2 fk到同一个表

时间:2013-01-15 11:19:05

标签: mysql sql select join left-join

join

|ID|admin|user |data|
|1 |00001|00002|XXXX|
  • admin(fk)= users.id
  • user(fk)= users.id

users

|id   |name|pass|type |
|00001|root|1234|admin|
|00002|user|1235|user |

select join.*,users.name as admin,users.name as user from join 
left join users on users.id=join.admin
left join users on users.id=join.user

where grrrrrrr

我该怎么做?

原始查询,我正在尝试运行:

SELECT

    visits.id,
    visits.patient AS patient_id,
    visits.doctor AS doctor_id,
    visits.date,
    visits.time_booked,
    visits.time_arrived,
    visits.time_start,
    visits.time_end,
    visits.type_id,
    visits.complain,
    visits.diagnosis,
    visits.note,
    visits.stats,
    (personal.name WHERE personal.id=visits.patient and personal.role='patient') AS pt_name,
    (personal.name WHERE personal.id=visits.doctor and personal.role='doctor') AS dr_name
    FROM
    visits ,
    personal

1 个答案:

答案 0 :(得分:2)

您必须使用不同的别名为表users添加别名。像

这样的东西
select 
  a.*,
  u1.name as admin,
  u2.name as user 
from `join` a 
left join users u1 on u1.id = a.admin
left join users u2 on u2.id = a.`user`;

此外,您必须转义表名joinuser,因为它们是MySQL中的保留关键字。尽量避免将这些名称作为对象名称。

SQL Fiddle Demo

这会给你:

| ID | ADMIN | USER | DATA |
----------------------------
|  1 |     1 |    2 | XXXX |

更新

在您更新问题后的查询中,您必须以同样的方式执行此操作,如下所示:

SELECT
  v.id,
  v.patient AS patient_id,
  v.doctor AS doctor_id,
  v.date,
  v.time_booked,
  v.time_arrived,
  v.time_start,
  v.time_end,
  v.type_id,
  v.complain,
  v.diagnosis,
  v.note,
  v.stats,
  pationts.name AS pt_name,
  doctors.name AS dr_name
FROM visits v
LEFT JOIN personal pationts  ON pationts.id   = v.patient 
                            AND pationts.role ='patient'
LEFT JOIN personal doctors   ON doctors.id    = v.patient 
                            AND doctors.role  ='doctor';

Updated SQL Fiddle Demo