Jump to content

[SOLVED] Query Question


therealwesfoster

Recommended Posts

Ok, I'm wanting to only show categories that have subcategories. Here is the SQL:

 

SELECT cat_title, cat_id,  FROM categories WHERE (SELECT COUNT(*) FROM subcats WHERE subcat_catid LIKE '%;cat_id;%')>0

 

(The sub-cat's subcat_catid field is setup to have more than 1 category. So if a sub-category was under 3 categories (1, 2, and 3), then the subcat_catid field would be ";1;2;3;".)

 

How can I get this part to work? WHERE subcat_catid LIKE '%;cat_id;%'.

 

------

 

Side question, how can I count how many sub-categories there are in the same query that grabs the main category information? I think it'd look like this:

SELECT cat_title, cat_id, (SELECT COUNT(*) FROM subcats....) as subcat_count  FROM categories

 

 

Thanks!

 

Wes

Link to comment
https://forums.phpfreaks.com/topic/144150-solved-query-question/
Share on other sites

Hrmmm my question was more of rhetorical (except for I thought you had a 1 to 1 relationship) ;p.  You should look into database normalization.

 

 

Basically the concept would be a middle-man table.

 

 

CREATE TABLE categories (

    cat_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,

    cat_name VARCHAR(255),

    cat_desc TEXT

);

 

CREATE TABLE cat_parents (

    cat_id INT NOT NULL,

    parent_id INT NOT NULL DEFAULT 0

);

 

Then, to show categories that have subcategories:

 

SELECT DISTINCT cp.parent_id as cat_id, c.cat_name, c.cat_desc FROM cat_parents cp JOIN categories c ON c.cat_id = cp.parent_id WHERE cp.parent_id != 0;

 

 

 

The query would of course have to be modified to work with your schema, but that would work with my sample schema.

 

 

Edit:  Forgot to put the cp alias after cat_parents.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.