I want to create a Grocery List Table that will accept both the Category and the Specific Products.
For Example: I add to my grocery list:
- Fruit (Category)
- Fuji Apple (Product)
- Shampoo (Category)
- Dove Energize Shampoo (Product)
I have Product Table w/ Manufacture开发者_运维百科r(reference table), Category Table w/ SubCategoryId.
I want the user to enter either the Category or Product into the Grocery List, but have a way knowing that item entered is either a Category or Product. Please advise.
Any help is much appreciated.
Bogdan solution is a very good solution and if i have your problem i would implement his solution, but if you insist on one column in one table for your grocery list, i guess you have to use substring
like e.g
CREATE TABLE grocery_list (
[groceryItem] varchar(100)
);
Insert into grocery_list ([groceryItem]) values ('(c)Fruit')
Insert into grocery_list ([groceryItem]) values ('(p)Fuji Apple')
Insert into grocery_list ([groceryItem]) values ('(c)Shampoo')
Insert into grocery_list ([groceryItem]) values ('(c)Dove Energize Shampoo')
and to access your table substring the first 2 chars to check the type of your item
Select [item] = case when substring(groceryItem,2,1) = 'c' then
right(groceryItem,len(groceryItem) - 3) + ' (Category)'
when substring(groceryItem,2,1) = 'p' then
right(groceryItem,len(groceryItem) - 3) + ' (Product)'
end
from grocery_list
This will give you the below result
**item**
Fruit (Category)
Fuji Apple (Product)
Shampoo (Category)
Dove Energize Shampoo (Category)
I would create two separate columns, one for categories and one for products:
CREATE TABLE grocery_list (
'category_id' INTEGER NULL FOREIGN KEY categories 'id',
'product_id' INTEGER NULL FOREIGN KEY products 'id',
...
);
Entries will only put a value in one of the two columns, leaving the other as NULL. Then you can query your grocery list like this:
SELECT * FROM grocery_list, categories, products
WHERE categories.id=grocery_list.category_id
AND products.id=grocery_list.product_id;
精彩评论