views:

39

answers:

3

I don't understand MySQL very well, here are the table structures I am using.

users

id | first_name | last_name | username | password

categories

id | user_id | name | description

links

id | user_id | category_id | name | url | description | date_added | hit_counter

I am trying to return a result set like this, to give information about the category for a user that includes how many links are in it.

id | user_id | name | description | link_count

At the moment I have this query, but it only returns rows for categories that have links. It should return rows for categories that do not have any links (empty categories).

SELECT categories.*, COUNT(links.id) FROM categories LEFT JOIN links ON categories.id=links.category_id;

How to do this query? Thanks.

+1  A: 

we can't do select table dot "star" with an aggregate.

what you wanna do is something like (pseudocode):

select
    categories.field1,
    categories.field2,
    {etc.}
    count(links.id)
from categories
left join links
    on categories.id = links.category_id
group by
    categories.field1,
    categories.field2,
    {etc.}

iow: you're missing the group by code-block to get the right aggregate in your query result set.

alien052002
why we can't do the select table dot "star" with an aggregate?we can do...this query will execute SELECT categories.*, COUNT(links.id) FROM categories LEFT JOIN links ON categories.id=links.category_id group by categories.id;
Kandhasamy
you're absolutely right, of course. :) but in the context of the poster's background stating: "i don't understand mysql very well", i didn't want to make a longer explanation about whatever fields listed in the aggregate function should be listed in the group box as well since most people lazily write count(*) instead of specific field count(fieldname) like the poster's questions. so i went with the general rule of thumb explanation of: "whatever you select, copy over those fields in the group by block". it's a "shoddy" excuse, i realize. so sorry.
alien052002
A: 

To mold alien052002's answer to fit your specific question, the following (untested) should work:

select c.id,
    c.user_id,
    c.name,
    c.description,
    count(l.link_count)
from categories c
left join links l on l.category_id = c.id
group by c.id, c.user_id, c.name, c.description
Harper Shelby
A: 

try this

SELECT categories.*, COUNT(links.id) FROM categories LEFT JOIN links ON categories.id=links.category_id group by categories.id;
Kandhasamy