I have two tables:
Product
------------------------------------
id group_id name quick_select
------------------------------------
1 1 product1 1
2 3 product2 0
3 5 product3 1
Product_group
-----------------------
id name parent_id
-----------------------
1 group1 0
2 group2 0
3 group3 1
4 group4 1
5 group5 3
I making a navigation system for quick select products. I show categories to user and user can navigate in them by clicking category button, then goes level down to subcategory and goes down so many levels that finally it can't go deeper - then I show products. First I show root categories where there's products under them and under those root categories subcategories, subsubcategories and so on.
In my query I want select all root categories (where parent_id=0), if there's products in them and in their subcategories and subsubcategories and so on, where quick_select must be 1 in product table. And I don't know the deepness of categories - how many levels there are.
Is it possible with one query? Or do I need to do two queries?
I made so far, with this query:
SELECT pg.id, pg.name, pg.parent_id AS parent_id
FR开发者_如何学编程OM product_group AS pg
LEFT JOIN product AS p ON pg.id = p.group_id
WHERE pg.parent_id = 0 AND p.id IS NOT NULL AND p.quick_select = 1
GROUP BY pg.id
But I don't receive root categories which subcategory is empty, which subcategory is empty and under this is one more subcategory with products with quick_select=1.
Sorry for my bad english.
I want to receive all categories where products with quick_select=1 are, not products
-- Category
| |
| product
|
-- Category
|
Category
|
Category
|
multiple products
The bad news is that you can't do this in SQLite, at least with this data structure, since SQLite doesn't support recursive SQL or window functions.
If select performance is important, you can try to organize the data like this: http://articles.sitepoint.com/article/hierarchical-data-database/2
Another option is to add the root id to each row at input time.
Basically, at some point you will have to use multiple selects and determine the root id at the application level.
Update: Ok, this is very much pseudo-code, but it should get you there.
You need a language that has some sort of hashmap or named array datatype.
hashmap results, parent, nodes, nodes_new; # variables
foreach (res in sql_execute("SELECT id, parent_id FROM product_group;") ) {
parent[res.id] = res.parent_id;
}
# get groups with products
foreach (res in sql_execute("SELECT pg.id FROM product_group AS pg INNER JOIN
product AS p ON pg.id = p.group_id
WHERE p.quick_select = 1 GROUP BY pg.id ") ) {
nodes[res.id] = res.id;
}
while (length(nodes) > 0) {
foreach (i in nodes) {
if (i = 0) { results[i] = i; } # if its a root node, add to results
else { nodes_new[parent[i]] = parent[i]; } # otherwise, add parent to the next round
}
nodes = nodes_new; # prepare for next round
}
print results;
精彩评论