A while ago, I asked for help on this SQL query. It shows snippets that belong to a parent category, using the category ID to tie them together. I tried to change it to show all categories, even when there’s no snippets inside but I can’t manage it.
I am sure this is not a PHP thing, as printing the result of this query does not show empty categories.
I just need help understanding this and what I need to change to make it show what I need it to.
Here’s the SQL:
SELECT c.id AS cid, c.slug AS cslug, c.name AS cname, s.id AS sid, s.name AS sname
FROM categories AS c
LEFT JOIN snippets AS s ON s.category = c.id
WHERE c.live=1 AND s.live=1 AND c.company='$company' AND s.company='$company'
ORDER BY c.name, s.name
Any tips and links to good resources to learn SQL would be appreciated too. 🙂
Here’s an example of what the query returns when run through PHP. SQL http://jsbin.com/obonal PHP Inefficient SQL Query
Move the snippet condition into the
onclause of the join.If you leave it in the
whereclause, result rows are required to match it, but missing rows from snippet will havenullvalues, sos.live=1will befalseand you’ll get no match.In the on clause, only rows from snippet are required to match it, but with the
left, matching is optional so you still get row from categories when snippet doesn’t match:The key part is the
join onclause, which can be arbitrarily complex, and in the example ofs.live=1do not have to be true “join” predicates (ie don’t have to compare values between tables – they can be just tests on the row itself):Note that some databases, eg mysql, allow your original syntax to still work as desired.
EDITED Moved s.company=’$company’ into the on clause too. Thanks @Andriy