The query I provided doesn't match your desired output format. My query builds "full transaction" combinations, but you want all distinct subset combinations (pairs, triplets, etc.) from transactions, with a specific format.
Let me correct the approach:
WITH RECURSIVE ordered AS (
-- For each transaction, order products by ID
SELECT
transaction_id,
product_id,
ROW_NUMBER() OVER (PARTITION BY transaction_id ORDER BY product_id) AS rn
FROM transactions
WHERE product_id IS NOT NULL
),
product_pairs AS (
-- Generate all possible product pairs from each transaction
SELECT
a.product_id AS product_id1,
b.product_id AS product_id2
FROM ordered a
JOIN ordered b ON a.transaction_id = b.transaction_id AND a.product_id < b.product_id
),
product_triplets AS (
-- Generate all possible product triplets from each transaction
SELECT
a.product_id AS product_id1,
b.product_id AS product_id2,
c.product_id AS product_id3
FROM ordered a
JOIN ordered b ON a.transaction_id = b.transaction_id AND a.product_id < b.product_id
JOIN ordered c ON b.transaction_id = c.transaction_id AND b.product_id < c.product_id
)
-- Combine all combinations with proper formatting
SELECT DISTINCT CONCAT('"', product_id1, '",', '"', product_id2, '"') AS combination
FROM product_pairs
UNION ALL
SELECT DISTINCT CONCAT('"', product_id1, '",', '"', product_id2, '",', '"', product_id3, '"') AS combination
FROM product_triplets
ORDER BY combination;
This query:
- Creates pairs of products from each transaction
- Creates triplets of products from each transaction
- Formats them as you specified with double quotes
- Returns distinct combinations
For your example data with transaction_id 231574 containing products 111, 222, 444, and transaction_id 137124 with just product 111, the output would be:
combination
"111","222"
"111","444"
"222","444"
"111","222","444"
Note: This approach explicitly handles pairs and triplets. If you need to support larger combinations (4+ products), you'd need additional JOINs or a different approach.