phpcodeignitergroup-bycountquery-builder

Count the number of joined record and parent record using CodeIgniter's query builder


I have two tables, X and Y

X:

Y:

I supply a user_id and a type_id, each user can have several entries in X with the same type_id.

I need to count all the entries in Y that match the criteria above. (hopefully I made myself clear ;))

So basically: From entries on X that match a user_id and type_id, grab all entries on Y that have the same x_id.

This is a query I was attempting in CodeIgniter (but any sort of MYSQL would be fine):

  $this->db->select("X.description, COUNT(Y.x_id) AS count ");
    $this->db->from("X");
    $this->db->join("Y", "Y.x_id=X.x_id");
    $this->db->where("X.type_id", 1);
    $this->db->where("X.user_id", 2);

This is only returning me 1 entry though.


Solution

  • Based on this "I need to count all the entries in Y that match the criteria above " you can try this:

    SELECT 
        COUNT(*) 
    FROM 
        x 
    INNER JOIN y
        ON x.x_id = y.x_id
    WHERE 
        x.type_id = 1
        AND x.user_id = 2
    

    UPDATE: If you want to count per description you need to group by it as mentioned by Ed Gibbs:

    SELECT 
        x.description,
        COUNT(*) 
    FROM 
        x 
    INNER JOIN y
        ON x.x_id = y.x_id
    WHERE 
        x.type_id = 1
        AND x.user_id = 2
    GROUP BY
        x.description