Self-relational table and recursive SQL function

I have a category table with:

  • CategoryId
  • parentCategoryID
  • CategoryName

and a table of elements with:

  • Itemid
  • CategoryId
  • ITEMNAME

I am using MySQL. I want to write a query that will return the number of elements in a category, taking into account the category identifier. The request should return a total score for all elements in all subcategories of this category.

Hope this makes sense. Sorry if I do not use the correct nomenclature.

+3
source share
4 answers

, , , join/alias . , -.

, "", - :

SELECT top.categoryID, top.categoryName, bottom.categoryID, bottom.categoryName,
    COUNT (items.itemID)
FROM categories AS top
LEFT JOIN categories AS bottom ON top.categoryID = bottom.parentCategoryID
LEFT JOIN items ON bottom.categoryID = items.categoryID
WHERE (bottom.categoryID = $your_category)
GROUP BY top.categoryID, bottom.categoryID

, WHERE, .

0

, , Jeff Dege, Adjacency:

, , ( SQL BETWEEN , , ), ( ) LIKE '[path]%' ( , MySQL, ) .

, . (, 1.2.3.).

You might want to conduct your own tests to compare these approaches, especially if you have many categories (several thousand or more).

0
source

Source: https://habr.com/ru/post/1764775/


All Articles