2017-07-22 28 views
1

我有一個下面的示例表。我試圖創建一個SQL查詢,獲取當前用戶的user_id以外的所有user_id,然後按照當前user_id的行數匹配該行。例如,如果用戶的user_id爲'1',我想獲取與id 2-8的行相對應的所有user_id,然後將user_id從大多數匹配項排序到當前用戶的行,以至少與當前用戶的行匹配通過匹配到特定行的SQL順序

讓我們假設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 | 
+----------+---------+-------+--------+-------+ 

回答

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表示真,0表示假。

如果你想成爲愛好者,你可以通過總差下令:

order by (abs(a.cars - a1.cars) + abs(a.houses - a1.houses) + abs(a.boats - a1.boats)); 

這被稱爲曼哈頓距離,你會實現一個版本近鄰模型。