如何查询以选择以下朋友:
用户表
+--------+--------------+-------------+
| id | first_name | last_name |
+--------+--------------+-------------+
| 1 | John | Doe |
| 2 | Andrew | Quin |
| 3 | Sara | Cambel |
| 4 | Samanda | Mint |
| 5 | Bill | Smith |
+--------+--------------+-------------+
朋友表
+--------+---------------+---------------+
| id | user_one_id | user_two_id |
+--------+---------------+---------------+
| 1 | 1 | 2 |
| 2 | 1 | 5 |
| 3 | 1 | 4 |
| 4 | 1 | 3 |
+--------+---------------+---------------+
当我们搜索" s"在id为1的用户的朋友中,结果应为:
| 4 | Samanda | Mint |
| 3 | Sara | Cambel |
| 5 | Bill | Smith |
" Samanda Mint"排在第一位,因为" s"角色处于第一位置,对于#34; Sara Cambel"," Sam"按字母顺序排在" Sar"。
之前"比尔史密斯"是第三,因为它包含" s"性格,但" s"之后的位置是以前的名字。
" Andrew Quin"结果不是因为没有" s"名字中的人物。
当前查询
SELECT u.id, u.first_name, u.last_name
FROM friends f
LEFT JOIN users u ON u.id=f.user_two_id
WHERE f.user_one_id=1 AND LOWER(u.first_name || ' ' || u.last_name) LIKE :query;
答案 0 :(得分:4)
使用辅助列full_name
select u.id, first_name, last_name
from users u
join friends f on user_two_id = u.id,
lower(concat(first_name, last_name)) full_name
where user_one_id = 1
and full_name like '%s%'
order by position('s' in full_name), full_name;
id | first_name | last_name
----+------------+-----------
4 | Samanda | Mint
3 | Sara | Cambel
5 | Bill | Smith
(3 rows)