【问题标题】:Searching friends alphabetically in PostgreSQL在 PostgreSQL 中按字母顺序搜索朋友
【发布时间】:2017-06-09 09:24:06
【问题描述】:

应该如何查询来选择喜欢的朋友:

用户表

+--------+--------------+-------------+
|   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             |
+--------+---------------+---------------+

当我们在 id 为 1 的用户的朋友中搜索“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;

【问题讨论】:

  • 显示您目前提出的查询。
  • @eurotrash 我添加了当前查询

标签: sql postgresql


【解决方案1】:

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

【讨论】:

  • 当我看到这个答案时,我终于明白了这个问题 - 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 2011-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多