I'm having trouble creating an appropriate sql query for this situation. I have 1 table where CATEGORY_ID is stored.
p_xref
+-------------+
| CATEGORY_ID |
+-------------+
| 5005 |
+-------------+
This CATEGORY_ID is the parent category and it may have child category IDs. I check for this in my next table. For each CATEGORY_ID in this table there is a PARENT_CAT_ID. If there is no parent for that category, it is set at -1. My query currently looks for a match between PARENT_CAT_ID and the CATEGORY_ID in the first table.
category_profile
+-------------+---------------+
| CATEGORY_ID | PARENT_CAT_ID |
+-------------+---------------+
| 5028 | 5005 |
| 5005 | -1 |
+-------------+---------------+
I then match this category ID with the final table in order to grab an ITEM_ID.
item_xref
+-------------+---------+
| CATEGORY_ID | ITEM_ID |
+-------------+---------+
| 5028 | 6767 |
+-------------+---------+
The problem with my current query is that it only grabs the children categories, and does not work for parent categories. I can do the opposite and match all parent categories and no child categories. Is there anyway to combine the two queries?
Query 1:Grabs child category matches only
SELECT DISTINCT DATE FROM promotion p
LEFT JOIN p_xref pcx ON p.P_ID = pcx.P_ID
LEFT JOIN category_profile cp ON pcx.CATEGORY_ID = cp.PARENT_CAT_ID
LEFT JOIN item_xref icx ON cp.CATEGORY_ID = icx.CATEGORY_ID
WHERE icx.ITEM_ID = "randomID"
Query 2:Grabs parent category matches only
SELECT DISTINCT DATE FROM promotion p
LEFT JOIN p_xref pcx ON p.P_ID = pcx.P_ID
LEFT JOIN item_xref icx ON pcx.CATEGORY_ID = icx.CATEGORY_ID
WHERE icx.ITEM_ID = "RandomID"
Thank you!