2

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
4

1 回答 1

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 小提琴演示

这会给你:

| 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';

更新的 SQL Fiddle 演示

于 2013-01-15T11:20:28.983 回答