2016-01-12 86 views
0

我有以下查詢:Mysql的內部連接 ​​- >如果返回null空,否則返回名字

SELECT 
    projects.id AS project_id, 
    projects.name AS project_name, 
    projects_tasks.id AS task_id, 
    projects_tasks.name AS task_name, 
    projects_tasks_timings.id AS timing_id, 
    projects_tasks_timings.registered_time AS timing_time, 
    projects_tasks_timings.edit_reason AS timing_description, 
    projects_tasks_timings.date AS timing_date, 
    projects_tasks_timings.created_at AS timing_date2, 
    projects_tasks_timings.updated_at AS timing_date3, 
    users.name AS timing_user_name, 
    users.surname AS timing_user_surname, 
    users2.name AS timing_user_name_update, 
    users2.surname AS timing_user_surname_update 
FROM `projects_tasks_timings` 
INNER JOIN `users` 
    ON users.id = projects_tasks_timings.user_id 
INNER JOIN `users` 
    AS users2 ON users2.id = projects_tasks_timings.updated_by 
INNER JOIN `projects_tasks` 
    ON projects_tasks.id = projects_tasks_timings.task_id 
INNER JOIN `projects` 
    ON projects.id = projects_tasks.project_id 
$task_clause 
$user_clause 
LIMIT $limit OFFSET $start 

這將返回大量的數據,但它沒有。我認爲因爲users2上的inner join與任何列都不匹配,因爲它們都是null值。

我想實現的是:

如果沒有匹配它應該返回null。如果有匹配,它應該返回用戶的名字。

我已經通過使用內部連接的where子句來查看一些問題,但迄今爲止沒有成功。

任何人都可以幫助我嗎?謝謝!

回答

2

只需使用LEFT JOIN代替如果INNER JOIN

SELECT 
    projects.id AS project_id, 
    projects.name AS project_name, 
    projects_tasks.id AS task_id, 
    projects_tasks.name AS task_name, 
    projects_tasks_timings.id AS timing_id, 
    projects_tasks_timings.registered_time AS timing_time, 
    projects_tasks_timings.edit_reason AS timing_description, 
    projects_tasks_timings.date AS timing_date, 
    projects_tasks_timings.created_at AS timing_date2, 
    projects_tasks_timings.updated_at AS timing_date3, 
    users.name AS timing_user_name, 
    users.surname AS timing_user_surname, 
    users2.name AS timing_user_name_update, 
    users2.surname AS timing_user_surname_update 
FROM `projects_tasks_timings` 
INNER JOIN `users` 
    ON users.id = projects_tasks_timings.user_id 
INNER JOIN `projects_tasks` 
    ON projects_tasks.id = projects_tasks_timings.task_id 
INNER JOIN `projects` 
    ON projects.id = projects_tasks.project_id 
LEFT JOIN `users` 
    AS users2 ON users2.id = projects_tasks_timings.updated_by 
$task_clause 
$user_clause 
LIMIT $limit OFFSET $start 
+0

感謝,這對我的作品:) –

相關問題