Select products where the category belongs to any category in the hierarchy

前端 未结 9 1638
再見小時候
再見小時候 2021-02-06 05:39

I have a products table that contains a FK for a category, the Categories table is created in a way that each category can have a parent category, example:

Compu         


        
9条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 06:17

    I have done similar things in the past, first querying for the category ids, then querying for the products "IN" those categories. Getting the categories is the hard bit, and you have a few options:

    • If the level of nesting of categories is known or you can find an upper bound: Build a horrible-looking SELECT with lots of JOINs. This is fast, but ugly and you need to set a limit on the levels of the hierarchy.
    • If you have a relatively small number of total categories, query them all (just ids, parents), collect the ids of the ones you care about, and do a SELECT....IN for the products. This was the appropriate option for me.
    • Query up/down the hierarchy using a series of SELECTs. Simple, but relatively slow.
    • I believe recent versions of SQLServer have some support for recursive queries, but haven't used them myself.

    Stored procedures can help if you don't want to do this app-side.

提交回复
热议问题