Prova questo
SELECT
a_product_id,
COALESCE( b_product_id, 'no_matchs_found' ) AS closest_product_match
FROM (
SELECT
*,
@row_num := IF(@prev_value=A_product_id,@row_num+1,1) AS row_num,
@prev_value := a_product_id
FROM
(SELECT @prev_value := 0) r
JOIN (
SELECT
a.product_id as a_product_id,
b.product_id as b_product_id,
count( distinct b.Attributes ),
count( distinct b2.Attributes ) as total_products
FROM
products a
LEFT JOIN products b ON ( a.Attributes = b.Attributes AND a.product_id <> b.product_id )
LEFT JOIN products b2 ON ( b2.product_id = b.product_id )
/*WHERE */
/* a.product_id = 3 */
GROUP BY
a.product_id,
b.product_id
ORDER BY
1, 3 desc, 4
) t
) t2
WHERE
row_num = 1
La precedente query
ottiene le closest matches
per tutti i prodotti, puoi includere il product_id
nella query più interna, per ottenere i risultati per un particolare product_id
, ho usato LEFT JOIN
in modo che anche se un product
non ha corrispondenze, è visualizzato
Spero che questo aiuti