代码之家  ›  专栏  ›  技术社区  ›  Ivar

MySQL:如果联接期间缺少表行,则“忽略”

  •  0
  • Ivar  · 技术社区  · 14 年前

    我在三个表上执行左联接,其中表“time”不一定包含任何匹配的行。但如果在该表中找不到匹配的行,则链接的数据将消失。

    SELECT
        w.date AS worker_date,
        w.name AS worker_name,
        w.address AS worker_address,
        w.zip AS worker_zip,
        w.place AS worker_place,
        w.phone AS worker_phone,
        w.email AS worker_email,
        w.company AS worker_company,
        w.accessibility AS worker_accessibility,
        c.date AS client_date,
        c.name AS client_name,
        c.address AS client_address,
        c.zip AS client_zip,
        c.place AS client_place,
        c.phone AS client_phone,
        c.email AS client_email,
        c.web AS client_web,
        c.contact AS client_contact,
        j.date AS job_date,
        j.client_id,
        j.worker_id,
        j.name AS job_name,
        j.description AS job_description,
        j.type AS job_type,
        j.status AS job_status,
        j.proof AS job_proof,
        j.deadline AS job_deadline,
        j.price AS job_price,
        j.final_client AS job_final_client,
        SUM(t.hours) AS time_hours
    FROM
        jobs AS j
    LEFT JOIN (
        workers AS w,
        clients AS c,
        time AS t
    ) ON (
        w.id = j.worker_id AND
        c.id = j.client_id AND
        j.id = t.job_id
    ) GROUP BY
        j.id;
    

    我该怎么做?

    提前谢谢你。

    3 回复  |  直到 14 年前
        1
  •  1
  •   ajreal    14 年前

    添加

    WHERE t.job_id IS NOT NULL 之前 GROUP BY

    尝试替换

    SUM(t.hours) AS time_hours

    (SELECT IFNULL(SUM(t.hours),0) FROM time WHERE time.job_id=j.job_id) AS time_hours

    从连接中删除时间

        2
  •  0
  •   Sandeepan Nath    14 年前

    我认为您的基本查询是正确的(大括号下有join)

    只是替换

    SUM(t.hours) AS time_hours
    

    具有

    SUM(if(t.hours is NULL,0,t.hours)) AS time_hours
    
        3
  •  0
  •   georgepsarakis    13 年前

    我不确定这是否是这里的问题,但是在某个MySQL版本之后,commas vs join的行为发生了变化。试试这个

     ...
     FROM jobs AS j LEFT JOIN workers AS w ON w.id = j.worker_id
     LEFT JOIN clients AS c c.id = j.client_id
     LEFT JOIN `time` AS t ON j.id = t.job_id
     ... 
    

    也可以按照@ajreal的建议用IFNULL修改总和。