简体   繁体   中英

Multiple Left Joins cause Wrong Sum

I got a MySQL Database where I store ship employees and their job experience. I got one table where I store the employees, one table where I store their previous jobs in the shipping department ( Type of Job , Years ) and another one table where I store their other previous jobs ( Type of Hob , Years ). All these are connected using the ID of the employee. When I fetch an employee I'd like to get the sum of his shipping and general experience, but the select query returns wrong sum for the general experience. I know this is cause by the multiple joins and because the tables are not joined properly, but I am not sure on how to fix this. Could you please help me?

PS I 'd like to do this with a single query.

Example of the query I use

SELECT id , name , SUM( s_exp.years ) , SUM ( g_exp.years ) 
FROM employees
LEFT JOIN s_exp ON employees.id = s_exp.id ,
LEFT JOIN g_exp ON employees.id = g_exp.id
GROUP BY employees.id

Maybe something like this:

SELECT id , name , 
(
    SELECT
        SUM(s_exp.years)
    FROM
        s_exp
    WHERE
        employees.id = s_exp.id
) AS s_total_years,
(
    SELECT
        SUM(g_exp.years)
    FROM
        g_exp
    WHERE
        employees.id = g_exp.id
) AS g_total_years,
FROM employees
Select id, sum(g_exp.years) GE, sum(s_exp.years) SE 
From s_exp Natural Join g_exp 
Where id = (Select id From employee Where name = ?)
group by id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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