Jump to content

Recommended Posts

I need to build a hierarchical product category table with data from another table.

 

The original product info table has a basic structure:

ID | SKU | Category1 | Category2 | Category3

1 | 001 | Apparel | Boots | Work Boots

2 | 002 | Apparel | Shirts | Long Sleeve

 

The categories table this is going into:

ID | Name | Parent_ID

1 | Apparel | 0

2 | Boots | 1

3 | Work Boots | 2

4 | Shirts | 1

5 | Long Sleeve | 4

 

 

I've been trying to use PHP to increment ID's by:

SELECT DISTINCT Category1

SELECT DISTINCT Category1,Category2

SELECT DISTINCT Category1, Category2, Category3

$i='0';
while ($row = mysql_fetch_assoc($result)) {
$i++;
echo $i . " - ". $row['Category1'] . "<br>";
}

One problem is that I can't get the parent ID that was generated in this method.  Another is that Category2 and 3 are not uniquely named at all.

 

So my question is, how do I distinctly select all three categories, and get each parent ID also?

For each category column $i in the original table:

- Get the distinct names. If $i isn't the first column, remember the name of each column's parent column at $i-1;

- If $i is not the first column: get the name-id pairs using the parent column names from the previous step;

- Insert the distinct names into the new table, giving parent_id=0 for the first $i, and giving the parent_id of their parent column for other $i.

 

If you have columns of the same name at the same level, you'll get into trouble. Other than that, this algorithm should work.

use this 3 queries

INSERT INTO categories SELECT DISTINCT '', Category1, 0 FROM product

INSERT INTO categories SELECT '', Category2, id FROM
(SELECT DISTINCT category1, Category2, categories.ID AS id FROM product, categories
WHERE product.Category1=categories.Name AND categories.Parent_ID=0) AS tbl1


INSERT INTO categories SELECT '', Category3, id FROM
(SELECT DISTINCT category1, Category2, Category3, c1.ID AS id FROM product, categories AS c, categories AS c1
WHERE product.Category1=c.Name AND c.Parent_ID=0 AND product.Category2=c1.Name AND c1.Parent_ID=c.ID) AS tbl1

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.