Jump to content

[SOLVED] (Simple?) counting question - data from 2 tables


kuma

Recommended Posts

I have 2 tables, genres and products. I'm trying to count the number of products in each genre where the genre's parent_id = 0. Here's my attempt:

 

SELECT products.genre_id, COUNT(*) FROM products GROUP BY genre_id, genres.genre_id FROM products, genres WHERE (genres.parent_id = '0' AND genres.genre_id = products.genre_id);

 

I get: "ERROR 1064 (42000): You have an error in your SQL syntax;"

 

Any help would be great! This seems like a simple query but I can't figure out the correct syntax.

 

MySQL server version: 5.0.37

 

Table Structure:

categories:

+-----------+--------------+------+-----+---------+-------+

| Field    | Type        | Null | Key | Default | Extra |

+-----------+--------------+------+-----+---------+-------+

| genre_id  | int(11)      | NO  | PRI |        |      |

| parent_id | int(11)      | NO  |      | 0      |      |

| name      | varchar(100) | NO  |    |        |      |

+-----------+--------------+------+-----+---------+-------+

 

products:

+----------+--------------+------+-----+---------+-------+

| Field    | Type        | Null | Key | Default | Extra |

+----------+--------------+------+-----+---------+-------+

| id      | int(11)      | NO  | PRI |        |      |

| shop_id  | int(11)      | NO  |    |        |      |

| genre_id | int(11)      | NO  |    |        |      |

| title    | varchar(255) | NO  |    |        |      |

+----------+--------------+------+-----+---------+-------+

 

 

Link to comment
Share on other sites

You have the group by in the wrong place... try (untested):

 

SELECT products.genre_id, COUNT(*) FROM products FROM products LEFT JOIN genres ON (genres.genre_id = products.genre_id WHERE genres.parent_id = '0' GROUP BY genres.genre_id 

Link to comment
Share on other sites

That worked, thank you very much!

 

(There was a typo in the code. Here's what worked if anyone needs it)

SELECT products.genre_id, COUNT(*)  FROM products LEFT JOIN genres ON (genres.genre_id = products.genre_id) WHERE genres.parent_id = '0' GROUP BY genres.genre_id;

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.