mysql左两次加入同一个表

时间:2012-04-23 15:19:12

标签: php mysql left-join

我试图两次加入同一张桌子,但这给了我一些问题。我有两张表ee_allee_calendar_events,我想加入。

SELECT
    u.first_name,
    u.last_name,
    u.email,
    SUM(e1.total_vacation_hours_earned) AS vacation_hours_earned,
    SUM(e2.absent_hours)
FROM ee_all AS u 
LEFT JOIN ee_calendar_events AS e1 ON u.user_id = e1.sched_user_id
LEFT JOIN ee_calendar_events AS e2 ON u.user_id = e2.sched_user_id AND e2.event_id = 2
WHERE
    u.user_id = 23

vacation_hours_earned列应该返回133,如果我取出第二个连接,它会返回。但是当我添加它时,查询将永远持续,vacation_hours_earned的值为2000或其他(这是错误的)。我的猜测是,当我添加第二个连接时,它再次对行进行求和,但我不是那样的。我已经尝试了几个小时,但无法找到解决方法,感谢任何帮助。

3 个答案:

答案 0 :(得分:3)

当最右边的表(第二个连接)具有与左边的表表达式的行对应的多个行时,左侧表表达式的行被复制并在SUM中计数多次。改为使用子查询。

SELECT
    u.first_name,
    u.last_name,
    u.email,
    (
        SELECT
            SUM(e1.total_vacation_hours_earned)
        FROM
            ee_calendar_events AS e1
        WHERE
            u.user_id = e1.sched_user_id
    ) AS vacation_hours_earned,
    (similar) AS absent_hours
FROM
    ee_all AS u
WHERE
    u.user_id = 23

答案 1 :(得分:3)

使用一些MySQL语法,您可以消除第二个左连接并简化查询;

SELECT
    u.first_name,
    u.last_name,
    u.email,
    SUM(e1.total_vacation_hours_earned) AS vacation_hours_earned,
    SUM(e1.absent_hours * (event_id=2))
FROM ee_all AS u 
LEFT JOIN ee_calendar_events AS e1 ON u.user_id = e1.sched_user_id
WHERE
    u.user_id = 23

演示here

答案 2 :(得分:0)

SELECT
    u.first_name,
    u.last_name,
    u.email,
    SUM(e1.total_vacation_hours_earned) AS vacation_hours_earned,    
   (select SUM(e2.absent_hours) as absenthours from ee_calendar_events AS e2 where u.user_id = e2.sched_user_id AND e2.event_id = 2)    
    FROM ee_all AS u 
    LEFT JOIN ee_calendar_events AS e1 ON u.user_id = e1.sched_user_id
    WHERE
    u.user_id = 23