gpt4 book ai didi

sql - 在 PostgreSQL 中按字母顺序搜索 friend

转载 作者:行者123 更新时间:2023-11-29 14:09:41 26 4
gpt4 key购买 nike

应该如何查询来选择像这样的 friend :

用户表

+--------+--------------+-------------+
| id | first_name | last_name |
+--------+--------------+-------------+
| 1 | John | Doe |
| 2 | Andrew | Quin |
| 3 | Sara | Cambel |
| 4 | Samanda | Mint |
| 5 | Bill | Smith |
+--------+--------------+-------------+

friend 表

+--------+---------------+---------------+
| id | user_one_id | user_two_id |
+--------+---------------+---------------+
| 1 | 1 | 2 |
| 2 | 1 | 5 |
| 3 | 1 | 4 |
| 4 | 1 | 3 |
+--------+---------------+---------------+

当我们在 id 为 1 的用户的 friend 中搜索“s”时,结果应该是:

| 4      | Samanda      | Mint        |
| 3 | Sara | Cambel |
| 5 | Bill | Smith |

“Samanda Mint”在列表中排在第一位,因为“s”字符在第一位,“Sara Cambel”也是如此,“Sam”按字母顺序排在“Sar”之前。

“Bill Smith”排在第三位,因为它包含“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;

最佳答案

使用辅助列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)

关于sql - 在 PostgreSQL 中按字母顺序搜索 friend ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44454077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com