左连接选择使用Propel ORM

时间:2015-06-18 07:40:15

标签: mysql join orm propel

我有3张桌子

主要表格:

+----+------------+
| id | major      |
+----+------------+
|  1 | Computer   |
|  2 | Architect  |
|  3 | Designer   |
+----+------------+

教室桌:

+----+----------+-------+
| id | major_id | name  | 
+----+----------+-------+
|  1 | 1        | A     |
|  2 | 1        | B     |
|  3 | 1        | C     |
|  4 | 2        | A     |
|  5 | 2        | B     |
|  6 | 3        | A     |
+----+----------+-------+

最后,student_classroom表

+----+------------+--------------+----------+
| id | student    | classroom_id | status   | 
+----+------------+--------------+----------+
|  1 | John       | 1            | Inactive |
|  2 | Defou      | 2            | Active   |
|  3 | John       | 2            | Active   |
|  4 | Alexa      | 1            | Active   |
|  5 | Nina       | 1            | Active   |
+----+------------+--------------+----------+

如何使用propel来构建下面的查询

select 
    a.id,
    a.major,
    b.number_of_student,
    c.number_of_classroom
from major a

left join (
    select
        major.major_id,
        count(student_classroom.id) as number_of_student
    from major
    left join classroom on classroom.major_id = major.id
    left join student_classroom on student_classroom.classroom_id = classroom.id
    where student_classroom.`status` = 'Active'
    group by major_id
) b on b.major_id = a.major_id

left join (
    select
        major.major_id,
        count(classroom.id) as number_of_classroom
    from major
    left join classroom on classroom.major_id = major.id
    group by major_id
) c on c.major_id = a.major_id

因为我希望最终的结果是这样的,所以我花了好几个小时试图找出它而没有成功。

+----+------------+-------------------+---------------------+
| id | major      | number_of_student | number_of_classroom |
+----+------------+-------------------+---------------------+
|  1 | Computer   | 4                 | 3                   |
|  2 | Architect  | 0                 | 2                   |
|  3 | Designer   | 0                 | 1                   |
+----+------------+-------------------+---------------------+

1 个答案:

答案 0 :(得分:1)

试试这个

select 
    m.id, 
    m.major, 
    count(distinct s.id) as number_of_student , 
    count(distinct c.id) as number_of_classroom 
from major m
left join classroom c on 
    (m.id = c.major_id)
left join student_classroom s 
    on (s.classroom_id = c.id and c.major_id = m.id and s.status = 'active')  
group by m.id
order by m.id