Jump to content

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.

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.