我在下面有一个示例表。我正在尝试创建一个SQL查询,除了当前用户的user_id之外,还获取所有user_id,然后按照当前user_id的行匹配次数
例如,如果用户的user_id为'1',我想获取与id为2-8的行对应的所有user_id,然后将user_ids从大多数匹配顺序排列到当前用户的行至少与当前用户的行匹配
假设var current_user = 1
这样的事情:
SELECT user_id
FROM assets
WHERE user_id <> `current_user` and
ORDER BY most matches to `current_user`"
输出应该得到7,8,3,9,2
I would appreciate anyone's input on how I can effectively achieve this.
Table assets
+----------+---------+-------+--------+-------+
| id | user_id | cars | houses | boats |
+----------+---------+-------+--------+-------+
| 1 | 1 | 3 | 2 | 3 |
| 2 | 8 | 3 | 2 | 5 |
| 3 | 3 | 3 | 2 | 2 |
| 4 | 2 | 5 | 1 | 5 |
| 5 | 9 | 5 | 7 | 3 |
| 8 | 7 | 3 | 2 | 3 |
+----------+---------+-------+--------+-------+
答案 0 :(得分:2)
我认为你可以这样做:
select a.*
from assets a cross join
assets a1
where a1.user_id = 1 and a.user_id <> a1.user_id
order by ( (a.cars = a1.cars) + (a.houses = a1.houses) + (a.boats = a1.boats) ) desc;
在MySQL中,布尔表达式在数字上下文中被视为一个整数,其中1表示true,0表示false。
如果你想成为发烧友,可以按总差额订购:
order by ( abs(a.cars - a1.cars) + abs(a.houses - a1.houses) + abs(a.boats - a1.boats) );
这称为曼哈顿距离,您将实现最近邻居模型的版本。