0

I have a query thats joining two table, using the GROUP_CONCAT to get a comma separated list which is then being mapped to an array in an object

SQL:

    $sql = "SELECT *,
            GROUP_CONCAT(climb_attributes.attribute_id) as climb_attributes
            FROM climbs
            LEFT JOIN climb_attributes ON
            (climbs.id = climb_attributes.climb_id)
            GROUP BY climb_id
            ORDER BY climbs.id";

PHP

$all_climb_profiles[$climb->id]->attributes = explode(",", $climb->climb_attributes);

Nearly working perfectly, except I currently only get back results IF the climb_attributes table contains the climb id. Essentially a climb can still exist even if it doesn't have any attributes, but at the moment it has to have an attribute to be returned in the results.

I also need to join it to another table to get the attribute name for the attribute id...if you can help with that as well that would be great, I'm hoping I can figure that out though.

1 Answer 1

1

First, you should not be using * to select from all tables when using group by. You can safely take all the columns from the climb table.

The problem is that you are aggregating on a column in the second table, rather than the first. And, it is NULL if there is no match. So, a better query is:

SELECT c.*, GROUP_CONCAT(ca.attribute_id) as climb_attributes
FROM climbs c LEFT JOIN
     climb_attributes ca
     ON c.id = ca.climb_id
GROUP BY c.id
ORDER BY c.id;

EDIT:

If you want to list the strings, then something like this should work:

SELECT c.*, GROUP_CONCAT(a.name) as climb_attributes
FROM climbs c LEFT JOIN
     climb_attributes ca
     ON c.id = ca.climb_id LEFT JOIN
     attributes a
     ON ca.attribute_id = c.id
GROUP BY c.id
ORDER BY c.id
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, thank you, and for the explanation as well. Can you help me link the ca.attribute_id to a third table containing the name for the attribute_id, its just has id and attribute_name column
I've been trying to figure work out how I can turn the ca.attribute_id into the actual value of the attribute_id, which is stored in a third table which just contains id and attribute columns, so rather than just a list of numbers, I get the actual value associated with the number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.