Is there a way to know or compare two tables, here are of course 5 tables.
Two act as linking Tables, while the other ones hold data.
SQL-query:
SELECT
c.name, isub.name
FROM subcategories isub
LEFT JOIN item_subcategory ic ON isub.subcategory_id = ic.subcategory_id
LEFT JOIN items i ON ic.item_id = i.item_id
LEFT JOIN categories c ON isub.category_id = c.category_id
LEFT JOIN item_category itmc ON c.category_id = itmc.category_id
WHERE i.name = 'Pepsi MAX';
SELECT
c.name, isub.name
FROM subcategories isub
LEFT JOIN item_subcategory ic ON isub.subcategory_id = ic.subcategory_id
LEFT JOIN items i ON ic.item_id = i.item_id and i.name = 'Pepsi'
LEFT JOIN categories c ON isub.category_id = c.category_id
LEFT JOIN item_category itmc ON c.category_id = itmc.category_id;
SELECT 'subcat' AS where_found
, isub.name
FROM items AS i
INNER
JOIN item_subcategory AS ic
ON ic.subcategory_id = i.subcategory_id
INNER
JOIN subcategories AS isub
ON isub.subcategory_id = ic.subcategory_id
WHERE i.name = 'Pepsi MAX'
UNION ALL
SELECT 'cat'
, c.name
FROM items AS i
INNER
JOIN item_category AS itmc
ON itmc.category_id = i.category_id
INNER
JOIN categories AS c
ON c.category_id = isub.category_id
WHERE i.name = 'Pepsi MAX'
Iām not sure I follow the sense of the join tables in your flow.
Since, by definition, a Subcategory has a Category, Why store item_category and item_subcategory separately?
I guess, I was stupid. I thought about having linking tables and then joining them. So if an item is in subcategory it would be joined with item_subcategory linking table.
Is this good approach?
I guess, this means that item can be in multiple categories, hmm! Bad design choice, I guess.
What would you suggest? Thanks a lot for pointing out!
Well this is where I make a suggestion and then get my wrist slapped by Rudy shortly thereafter
If it were me, iād combine the subcategory and category tables thusly:
If itās a Category, parent is 0, if itās a subcategory, parent is the ID of its parent category. Since youāve specified a 1-level hierarchy, this would satisfy all data storage.
You mean subcategory holds parent_id? Because thatās what I have in my sqlfiddle. But then I want to place an item inside a specific category or subcategory, so I used linking tables.
See, iāve always had it railed to me that you should avoid NULL columns at all costs, and the BIGINT was because iām matching the datatype of the ID column of the same table. (I didnt define that column. It probably doesnt need to be a BIGINT.)