Mysql内连接 - >如果null返回null,则返回名称

时间:2016-01-12 12:44:25

标签: mysql 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 `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

这应该返回大量数据,但事实并非如此。我认为因为inner join上的users2与任何列都不匹配,因为它们都是null值。

我想要实现的目标是:

如果没有匹配则应该返回null。如果有匹配项,则应返回用户名。

我在内连接上使用where子句查看了一些问题,但到目前为止没有成功。

任何人都可以帮我吗?谢谢!

1 个答案:

答案 0 :(得分:2)

如果INNER JOIN

,请使用LEFT 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