简体   繁体   English

MySQL Join显示具有相同值的多行

[英]MySQL Join is showing multiple rows with same value

I am trying to learn MySQL select statements a little better and I have somehow ended up selecting multiple rows with the same values. 我试图更好地学习MySQL select语句,但最终以某种方式选择了多个具有相同值的行。 If I remove the last JOIN the query comes out correctly, but I still need the tasks.Rate_Schedule_ID joined with hourlyrates.Rate_Schedule_ID, as shown in the last JOIN statement. 如果删除最后一个JOIN语句,查询将正确发出,但是我仍然需要task.Rate_Schedule_ID与hourlyrates.Rate_Schedule_ID结合在一起,如最后一个JOIN语句所示。

EDIT: It is duplicating once for each row. 编辑:它为每一行重复一次。 Here is a picture of the results I am getting. 这是我得到的结果的图片。

在此处输入图片说明

 SELECT 
 project_timecard_tasks.Task_ID, 
 project_timecard_tasks.DateTime,
 project_timecard_tasks.Total_Hours,
 project_timecard_tasks.User_ID,
 project_timecard_tasks.Project_ID,
 users.User_ID,users.FirstName,
 users.LastName,
 tasks.id,
 tasks.taskName, 
 tasks.billingOption,
 tasks.fixedRate,
 tasks.Rate_Schedule_ID,
 hourlyrates.Rate_Schedule_ID,
 hourlyrates.hourlyRate

FROM 
 project_timecard_tasks 

JOIN users ON project_timecard_tasks.User_ID = users.User_ID 
JOIN tasks ON project_timecard_tasks.Task_ID = tasks.id 
JOIN hourlyrates ON tasks.Rate_Schedule_ID = hourlyrates.Rate_Schedule_ID

WHERE 
 project_timecard_tasks.Project_ID = '$jobNumber'

The issue is that you have multiple rows in your result (from the tasks table) with the same Rate_Schedule_ID. 问题是您的结果(来自任务表)中有多行具有相同的Rate_Schedule_ID。 That means that for each of those, you get a match in your hourlyrates table, which gives you two matches for each row. 这意味着,对于其中的每一个,您都将在小时费率表中找到一个匹配项,从而为每一行提供两个匹配项。

You can change your SELECT to SELECT DISTINCT, which will fix the problem. 您可以将SELECT更改为SELECT DISTINCT,这将解决此问题。 But this might be an indication that there is a deeper problem in your data. 但这可能表明您的数据存在更深的问题。

The way to check if this is really the issue is to look at the result set without the last join. 检查这是否真的是问题的方法是查看没有最后连接的结果集。 If there are duplicate Rate_Schedule_IDs, then that's why it's duplicating rows. 如果有重复的Rate_Schedule_ID,那么这就是为什么要复制行的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM