Home > Database > Mysql Tutorial > How Can a Recursive SQL Query Group Matching Products by Minimum Product ID?

How Can a Recursive SQL Query Group Matching Products by Minimum Product ID?

Barbara Streisand
Release: 2025-01-05 11:27:39
Original
280 people have browsed it

How Can a Recursive SQL Query Group Matching Products by Minimum Product ID?

Recursive Query in SQL Server

To retrieve matching products grouped by their minimum Product ID, a recursive query can be employed. This query iterates through a table, traversing the Product_ID relationships, and accumulating the results in a separate groups table. The recursive structure ensures that all matches are identified and included in the results.

Solution:

WITH CTE
AS
(
    SELECT DISTINCT
        M1.Product_ID AS Group_ID,
        M1.Product_ID
    FROM matches M1
        LEFT JOIN matches M2
            ON M1.Product_Id = M2.matching_Product_Id
    WHERE M2.matching_Product_Id IS NULL
    UNION ALL
    SELECT
        C.Group_ID,
        M.matching_Product_Id
    FROM CTE C
        JOIN matches M
            ON C.Product_ID = M.Product_ID
)
SELECT * FROM CTE ORDER BY Group_ID
Copy after login

In this query, the CTE is a recursive definition that identifies the minimum Product_ID for each group. The query starts by selecting the Product_IDs that do not have a matching Product_Id, creating the initial groups. In the recursive step, the query joins the CTE with the matches table to identify matching Product_IDs and add them to the groups. This process continues until all matches are processed.

The final result is a table named groups that contains the MIN Product_ID for each group, along with all the Product_IDs that belong to that group. This structure enables efficient queries on product relationships and groupings.

Note:

To control the recursion depth, use the OPTION(MAXRECURSION n) clause, replacing n with the desired maximum recursion level.

Example: SQL Fiddle Demo

https://www.sqlfiddle.com/#!18/c772e/11

The above is the detailed content of How Can a Recursive SQL Query Group Matching Products by Minimum Product ID?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template