sql >> Database teknologi >  >> RDS >> Mysql

SQL- Valg af det mest lignende produkt

Prøv dette

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

Ovenstående query får de closest matches for alle produkterne kan du inkludere product_id i den inderste forespørgsel for at få resultaterne for et bestemt product_id , jeg har brugt LEFT JOIN så selvom et product har ingen resultater, den vises

SQLFIDDLE

Håber dette hjælper



  1. C++ Program, der kommunikerer med MySQL-databasen

  2. Forhindrer denne kode SQL-injektion?

  3. Amazon EC2, mysql afbryder start, fordi InnoDB:mmap (x bytes) mislykkedes; fejl nr 12

  4. Hvordan vælger man alle poster, der er 10 minutter inden for det aktuelle tidsstempel i MySQL?