Welcome Guest, Not a member yet? Register   Sign In
Active Record Query
#5

[eluser]jamesf[/eluser]
Basically in my database a project can have many elements and in my SQL i wanted to find the number of elements for each project that are 'Active'.

Code:
projects
    - id
    - name
    - status [enum(ACTIVE,INACTIVE)]

elements
    - id
    - project_id
    - name
    - status

So I needed to implement this SQL in active record which I was under the impression wasn't possible.

Code:
SELECT projects.*, num_elements
FROM projects
LEFT JOIN
(
    SELECT project_id, COUNT(*) as num_elements
    FROM elements
    WHERE status='Active'
    GROUP BY project_id
) as elements ON elements.project_id = projects.id
WHERE projects.status = 'ACTIVE'
GROUP BY projects.id

I thought you could apply a general where clause on a join table e.g.

Code:
$this->db->where("elements.status='ACTIVE'");

but if I add this only projects that have active elements are returned which wouldn't be correct. Not to worry too much about it, I've managed to find a solution but thanks for your help.


Messages In This Thread
Active Record Query - by El Forum - 05-22-2008, 08:36 AM
Active Record Query - by El Forum - 05-22-2008, 12:57 PM
Active Record Query - by El Forum - 05-23-2008, 03:01 AM
Active Record Query - by El Forum - 05-23-2008, 05:11 AM
Active Record Query - by El Forum - 05-23-2008, 07:49 AM



Theme © iAndrew 2016 - Forum software by © MyBB