我有一个用户表:
user_id | firstname | last name | picUrl ...
1 bob smith null
2 bobby smith null
3 rob smithies null
我还有一个朋友表:
friend1_id | friend2_id | status | date_established
1 2 accepted 2018-02-06 10:23:01
2 1 accepted 2018-02-06 10:23:01
我有一个简单的查询来根据条件($ searchString)搜索用户,并根据" best"进行排序。匹配:
$query = "SELECT user_id, firstname, lastname, picUrl, LOWER(CONCAT(firstname, ' ', lastname)) as fullname
FROM user
WHERE LOWER(CONCAT(firstname, ' ', lastname)) LIKE LOWER('%" . $searchString . "%') AND user_id != '{$userId}'
ORDER BY
CASE WHEN fullname = LOWER('" . $searchString . "') THEN 0
WHEN fullname = LOWER('" . $searchString . "%') THEN 1
WHEN fullname = LOWER('%" . $searchString . "%') THEN 2
WHEN fullname = LOWER('%" . $searchString . "') THEN 3
ELSE 4
END, fullname DESC
LIMIT 5";
查询将忽略当前用户:
user_id != '{$userId}'
因为你无法将自己添加为朋友。
如何忽略/不显示已经是朋友的用户?
示例
我是用户1。
我搜索"史密斯"。
=>我是用户1,所以我不是 显示。
=>用户2已经是我的朋友,所以他们没有显示。
=>只显示 Rob Smithies 。
答案 0 :(得分:3)
只需添加一个与friends'ids匹配的条件。更改您的查询如下
$query = "SELECT user_id, firstname, lastname, picUrl, LOWER(CONCAT(firstname, ' ', lastname)) as fullname
FROM user
WHERE LOWER(CONCAT(firstname, ' ', lastname)) LIKE LOWER('%" . $searchString . "%') AND (user_id != '{$userId}' AND user_id not in (SELECT friend1_id from friends where friend2_id = '{$userId}') AND user_id not in (SELECT friend2_id from friends where friend1_id = '{$userId}'))
ORDER BY
CASE WHEN fullname = LOWER('" . $searchString . "') THEN 0
WHEN fullname = LOWER('" . $searchString . "%') THEN 1
WHEN fullname = LOWER('%" . $searchString . "%') THEN 2
WHEN fullname = LOWER('%" . $searchString . "') THEN 3
ELSE 4
END, fullname DESC
LIMIT 5";