gpt4 book ai didi

MySQL 函数 : rank table by most similar attributes

转载 作者:可可西里 更新时间:2023-11-01 08:25:05 27 4
gpt4 key购买 nike

我有一个包含产品 ID关键字 的表格,如下所示:

+------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| product_id | int(10) unsigned | YES | MUL | NULL | |
| keyword | varchar(255) | YES | | NULL | |
+------------+------------------+------+-----+---------+----------------+

此表仅存储产品 ID 以及与这些产品关联的关键字。例如,它可能包含:

+----+------------+---------+
| id | product_id | name |
+----+------------+---------+
| 1 | 1 | soft |
| 2 | 1 | red |
| 3 | 1 | leather |
| 4 | 2 | cloth |
| 5 | 2 | red |
| 6 | 2 | new |
| 7 | 3 | soft |
| 8 | 3 | red |
| 9 | 4 | blue |
+----+------------+---------+

换句话说:

  • 产品 1 是柔软的红色皮革。
  • 产品 2 是布料,红色,全新。
  • 产品3是红色的,柔软的,
  • 产品 4 是蓝色的。

我需要一些方法来获取产品 ID,并取回按常用关键字数量排序的产品 ID 列表

例如,如果我传入 product_id 1,我希望返回:

+----+-------+------------+
| product_id | matches |
+------------+------------+
| 3 | 2 | (product 3 has two common keywords with product 1)
| 2 | 1 | (product 2 has one common keyword with product 1)
| 4 | 0 | (product 4 has no common keywords with product 1)
+------------+------------+

最佳答案

一个选项使用带有条件聚合的自右外连接来计算匹配名称之间的数量,例如产品 ID 1 和所有其他产品 ID:

SELECT t2.product_id,
SUM(CASE WHEN t1.name IS NOT NULL THEN 1 ELSE 0 END) AS matches
FROM yourTable t1
RIGHT JOIN yourTable t2
ON t1.name = t2.name AND
t1.product_id = 1
WHERE t2.product_id <> 1
GROUP BY t2.product_id
ORDER BY t2.product_id

点击下面的链接获取正在运行的演示:

SQLFiddle

关于MySQL 函数 : rank table by most similar attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38816773/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com