SELECT JOIN 在同一个表中的多行 [英] SELECT JOIN in same table ON multiple rows

查看:45
本文介绍了SELECT JOIN 在同一个表中的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 itemID 和 categoryID 列的表.两列都是主键,因为每个项目可以有 1 个以上的类别:

I have a table with an itemID and a categoryID columns. Both columns are primary keys because each item can have more than 1 category:

itemID  |  catID
-----------------
1        |  2
1        |  3
1        |  4
2        |  2
2        |  3
2        |  4

我想选择具有相同类别的项目(基于所有项目类别,而不仅仅是一个),所以我需要加入同一个表.

I want to select items with the same categories (based on all the item categories, not just one) so I need to kind of JOIN the same table.

我希望能够根据指定的 itemID 找到具有相同 catID 的 itemID.

I want to be able to find itemIDs with the same catIDs based on a specified itemID.

注意:例如,项目 1 的类别为 2、3、4、5、6,项目 2 的类别为 2、3、4、5、6,项目 3 的类别为 3、5,6 然后,如果我将项目 1 与项目 2 和 3 进行比较,我需要先获得项目 2,然后再获得项目 3,因为项目 2 的类别匹配比项目 3 多.显然,不仅需要对所​​有项目进行 3..这样我就可以推荐类似产品的访问者...

Note: For example item 1 have categories 2,3,4,5,6 and item 2 have categories 2,3,4,5,6 and item 3 have categories 3,5,6 then if i compare item 1 to item 2 and 3 i need to get item 2 first and then item 3 because item 2 have more categories matches than item 3.. Obviously it need to be done with all the items not only 3.. This way I can recommend visitors of similar products...

推荐答案

以 Bill 的初始查询为基础,这应该按照匹配的类别数按降序对其进行排序(因为连接应该为每个匹配返回一行).我还从结果中排除了正在查询的项目.

Building on Bill's initial query, this ought to order it in descending order by the number of categories matched (since the join should return one row per match). I also excluded the item being queried on from the result.

SELECT c2.itemID
FROM categories c1
JOIN categories c2 ON c1.catID = c2.catID
WHERE c1.itemID = :id
AND c2.itemID <> :id
GROUP BY c2.itemID
ORDER BY count(c2.itemID) DESC;

这篇关于SELECT JOIN 在同一个表中的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆