LEFT JOIN(mysql)

时间:2012-03-05 09:54:05

标签: mysql cakephp cakephp-1.3

如何离开乔治?

左表

SELECT TYPE , days
FROM leavetypes


type  days  
anual   10

casual  6

sick    10

右表

SELECT sub_leave_type, (
SUM( working_days )
) AS used
FROM vacations
WHERE `user_id` = '1'
AND `from_date`
BETWEEN '2012-01-01'
AND '2012-12-31'
GROUP BY sub_leave_type


sub_leave_type      used

anual               3

casual              6

实际上我在cakephp上这样做这是我的代码。

$allleaves = $this->Leavetype->find('all', array(
        'joins' => array(
            array(
                'table' => 'vacations',
                'alias' => 'vacationsJoin',
                'type' => 'left',
                'conditions' => array('vacationsJoin.sub_leave_type = Leavetype.type')
            )
        ),
        'conditions' => array(
            'vacationsJoin.user_id' => $_SESSION['Auth']['User']['id'],
            'vacationsJoin.from_date  BETWEEN ? and ?' => array(date('Y') . '-01-01',
                date('Y') . '-12-31')
        ),
        'fields' => array('type', 'days', '(SUM(working_days)) as used'),
        'group' => 'sub_leave_type',
            ));

    $this->set(compact('allleaves'));

这不是我想要的,我想要的是左表的所有行和其他来自假期表

2 个答案:

答案 0 :(得分:3)

请阅读此查询并根据您的要求进行更改

SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

答案 1 :(得分:1)

我说得对,这里的问题就是答案。主要问题在于GROUP

$allleaves = $this->Leavetype->find('all', array(
        'joins' => array(
            array(
                'table' => 'vacations',
                'alias' => 'vacationsJoin',
                'type' => 'left',
                'conditions' => array('vacationsJoin.sub_leave_type = Leavetype.type',
                     'vacationsJoin.user_id' => $_SESSION['Auth']['User']['id'],
            'vacationsJoin.from_date  BETWEEN ? and ?' => array(date('Y') . '-01-01',
                date('Y') . '-12-31'),'vacationsJoin.status'=>'approved'
                    )
            )
        ),

        'fields' => array('type', 'days', '(SUM(working_days)) as used'),
        'group' => 'type'
            ));
    $this->set(compact('allleaves'));