mysql左连接多列

时间:2012-03-02 18:19:44

标签: php mysql join

我正在为我的工作构建一个数据库,但我无法弄清楚如何构建此查询。

与我的问题相关的表是:

工作

Surgical_Planning - 作为外键的工作,存在一些工作,不存在其他工作

Medical_Model - 具有外键作业,与作业1对1的关系

这是一个有效的查询,我没有任何有关手术计划的信息

    SELECT
    job,
    physician_idphysician as Physician,
    patient_idpatient as Patient,
    status,
    DATE_FORMAT(scan_date, '%M %e, %Y, %l:%i%p') as Scan_Date,
    DATE_FORMAT(timestamp, '%M %e, %Y, %l:%i%p') as Recieved,
    DATE_FORMAT(date_required, '%M %e, %Y, %l:%i%p') as Date_Required
    FROM
    job, patient_has_physician as phys, Scan, Medical_Model as med
    WHERE
    Scan.job_job = job AND phys.job_job = job
    AND med.job_job = job AND job.type =  'medical

我想我想要做一个左连接,以便按顺序显示每个作业,上面的查询中包含所有信息,但是当有一个作业的Surgical_Planning时,我希望有一个列为那也是。这是我的尝试不起作用

    SELECT
    job,
    physician_idphysician as Physician,
    patient_idpatient as Patient,
    status,
    DATE_FORMAT(scan_date, '%M %e, %Y, %l:%i%p') as Scan_Date,
    DATE_FORMAT(timestamp, '%M %e, %Y, %l:%i%p') as Recieved,
    DATE_FORMAT(date_required, '%M %e, %Y, %l:%i%p') as Date_Required
    FROM
    job, patient_has_physician as phys, Scan, Medical_Model as med

    LEFT JOIN Surgical_Planning ON job.job = Surgical_Planning.job_job
    AND Scan.job_job = job AND phys.job_job = job
    AND med.job_job = job AND job.type = 'medical'

我可以按照我想要的方式运行这个基本的左连接,但是如果我想添加更多像上面这样的列,它就不起作用。

    SELECT job, planning_id
    FROM job
    LEFT JOIN Surgical_Planning ON job = Surgical_Planning.job_job

是否也可以使用子查询?我可以找出这些更基本的查询,但真的遇到了这些更复杂的连接和子查询问题。任何建议表示赞赏。

编辑---作业表架构


- 表mmrljob


DROP TABLE IF EXISTS mmrljob;

CREATE TABLE IF NOT NOT EXISTS mmrljob

job INT(11)NOT NULL AUTO_INCREMENT,

type VARCHAR(45)NULL,

status VARCHAR(45)NULL DEFAULT NULL,

timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP on UPDATE CURRENT_TIMESTAMP,

PRIMARY KEY(job))

ENGINE = InnoDB

DEFAULT CHARACTER SET = latin1;

1 个答案:

答案 0 :(得分:11)

变化

LEFT JOIN Surgical_Planning ON job.job = Surgical_Planning.job_job
AND Scan.job_job = job AND phys.job_job = job
AND med.job_job = job AND job.type = 'medical'

LEFT JOIN Surgical_Planning ON job.job = Surgical_Planning.job_job
WHERE Scan.job_job = job AND phys.job_job = job
AND med.job_job = job AND job.type = 'medical'

编辑:

左连接针对实际LEFT JOIN语法左侧的表。将作业移至列表的末尾,然后重试。

FROM patient_has_physician as phys, Scan, Medical_Model as med, job