可能是一个重复的问题...... 这里有两个表 tasks_0_tasks_staff 和 tasks_0_staff_time_management :
tasks_0_tasks_staff +----+---------+---------+ | id | task_id | user_id | +----+---------+---------+ | 1 | 1 | 348 | | 2 | 1 | 350 | | 3 | 2 | 350 | | 4 | 2 | 351 | | 5 | 2 | 357 | +----+---------+---------+
和
tasks_0_staff_time_management +----+---------+---------+-------------+-------+ | id | user_id | task_id | day_of_week | hours | +----+---------+---------+-------------+-------+ | 1 | 350 | 1 | 2 | 2 | | 2 | 350 | 1 | 3 | 3 | +----+---------+---------+-------------+-------+
当我执行以下查询时,它在左连接表中显示重复数据...我如何显示null(这是实际情况)......
SELECT tasks_0_tasks_staff.`task_id`, tasks_0_staff_time_management.day_of_week, tasks_0_staff_time_management.hours FROM tasks_0_tasks_staff LEFT JOIN `tasks_0_staff_time_management` ON `tasks_0_staff_time_management`.`user_id`= `tasks_0_tasks_staff`.`user_id` WHERE `tasks_0_tasks_staff`.`user_id`= 350 ORDER BY `tasks_0_tasks_staff`.`task_id` ; results: +---------+-------------+-------+ | task_id | day_of_week | hours | +---------+-------------+-------+ | 1 | 2 | 2 | | 1 | 3 | 3 | | 2 | 2 | 2 | | 2 | 3 | 3 | +---------+-------------+-------+
为什么结果中的最后两行显示 day_of_week 和小时列值,因为左连接表中不存在这些值?这两行如何显示 NULL 值...?
我期待结果像这样
+---------+-------------+-------+ | task_id | day_of_week | hours | +---------+-------------+-------+ | 1 | 2 | 2 | | 1 | 3 | 3 | | 2 | NULL | NULL | | 2 | NULL | NULL | +---------+-------------+-------+
答案 0 :(得分:2)
您必须像这样更改您的代码
SELECT tasks_0_tasks_staff.`task_id`,
tasks_0_staff_time_management.day_of_week,
tasks_0_staff_time_management.hours
FROM tasks_0_tasks_staff
LEFT JOIN `tasks_0_staff_time_management` ON `tasks_0_staff_time_management`.`user_id`= `tasks_0_tasks_staff`.`user_id`
WHERE `tasks_0_tasks_staff`.`user_id`= 350 AND `tasks_0_tasks_staff`.`task_id` = tasks_0_staff_time_management.`task_id`
ORDER BY `tasks_0_tasks_staff`.`task_id` ;
答案 1 :(得分:1)
您需要在您的位置添加条件,以便它只匹配具有相同task_id的记录。
请注意,重复的结果意味着不同的相关行是相同的,不您的情况。
答案 2 :(得分:1)
您应该在加入时添加SELECT * FROM table WHERE FIND_IN_SET($yourValue, column-name)
作为条件:
task_id
或者使用更多语义SQL:
SELECT tasks_0_tasks_staff.`task_id`,
tasks_0_staff_time_management.day_of_week,
tasks_0_staff_time_management.hours
FROM tasks_0_tasks_staff
LEFT JOIN `tasks_0_staff_time_management` ON `tasks_0_staff_time_management`.`user_id`= `tasks_0_tasks_staff`.`user_id` AND `tasks_0_staff_time_management`.`task_id`= `tasks_0_tasks_staff`.`task_id`
WHERE `tasks_0_tasks_staff`.`user_id`= 350
ORDER BY `tasks_0_tasks_staff`.`task_id` ;
这里有一点概念证明SQL小提琴:
答案 3 :(得分:0)
你应该使用" INNER JOIN"为了它。
SELECT tasks_0_tasks_staff.`task_id`,
tasks_0_staff_time_management.day_of_week,
tasks_0_staff_time_management.hours
FROM tasks_0_tasks_staff
INNER JOIN `tasks_0_staff_time_management` ON `tasks_0_staff_time_management`.`user_id`= `tasks_0_tasks_staff`.`user_id`
WHERE `tasks_0_tasks_staff`.`user_id`= 350
ORDER BY `tasks_0_tasks_staff`.`task_id` ;