gpt4 book ai didi

SQL(Postgres)为列表参数中的每个项目获取一行,其优先顺序由另一列指定

转载 作者:行者123 更新时间:2023-11-29 13:10:26 24 4
gpt4 key购买 nike

(使用最近的 postgres)

考虑表 contact_methods

id | person | contact_type | other_data
1 | 1 | "" | stuff
2 | 1 | "mobile" | important stuff
3 | 2 | "mobile" | still relevant
4 | 3 | "" | interesting

并要求为指定人员提取 1 种联系方法,并优先选择指定联系类型的行(不是空字符串“”)。

当我需要为一个人获取 contact_method 行时,我可以想出如何获得正确答案。给我联系人 1 的联系方式:

SELECT * FROM contact_methods WHERE person = '1' ORDER BY contact_type DESC LIMIT 1;

这将导致 ID 为 2 的行。

但我需要支持在单个查询中为一组人员获取一种联系方式的列表。例如。给我 [1, 2, 3] 人的结果

哪个应该导致 ID 为 2、3 和 4 的行。是否有一种在一个查询中执行此操作的有效方法?

最佳答案

在 Postgres 中,使用 DISTINCT ON:

SELECT DISTINCT ON (person) cm.* 
FROM contact_methods cm
WHERE person IN ('1', '2', '3')
ORDER BY person, contact_type DESC;

参见:http://www.postgresqltutorial.com/postgresql-select-distinct/

关于SQL(Postgres)为列表参数中的每个项目获取一行,其优先顺序由另一列指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55521376/

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