1

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!

4

2 回答 2

0

change this:

LEFT JOIN category_profile cp ON pcx.CATEGORY_ID = cp.PARENT_CAT_ID   

to this

JOIN category_profile cp ON pcx.CATEGORY_ID = cp.PARENT_CAT_ID   
or pcx.category_id = cp.category_id
于 2013-10-09T16:05:38.500 回答
0

我会从相反的方向开始以获取无论如何都要查找的项目,然后以另一种方式链接。通过使用 WHERE 子句,您可以强制进入 INNER 连接与 LEFT 连接。(没有生产表列的列表,但假设日期来自该表)

select distinct 
      p.Date
   from
      item_xref ixc
         JOIN category_profile cp
            on icx.category_id = cp.category_id
            LEFT JOIN p_xref x1
               on cp.category_id = x1.category_id
               OR cp.parent_cat_id = x1.category_id
               left join promotion p
                  on x1.category_id = p.p_id
   where
      icx.item_id = "randomid"

确保在 item_id 上的 item_xref 表上的索引 category_id 上 category_profile 上的索引

于 2013-10-09T16:33:47.390 回答