gpt4 book ai didi

python - 从 sql 表中选择值对

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

我有一个包含 3 列的 SQL 表:“从点”、“到点”和点之间的“距离”。对于特定的一对点,始终只有一个距离。

| from | to  | distance |
|-----------------------|
| 1 | 2 | 15 |
| 1 | 3 | 20 |
| 1 | 4 | 2 |
| 3 | 2 | 16 |
| 4 | 2 | 48 |
| 5 | 2 | 12 |
| 3 | 4 | 19 |
| 3 | 5 | 55 |
| 4 | 5 | 18 |

现在我有一个点列表,我想得到它们之间的距离,例如:

ids = [1, 2, 4]

我想返回这些点之间的所有距离:

1-2 -> 15
1-4 -> 2
2-4 -> 48

我在 python 中编写了一些代码来获取这些对

    pairs=[]
for a in ids:
for b in ids:
if a != b and sorted([a,b]) not in trasy:
pairs.append(sorted([a,b]))
print(sorted([a,b]))

我可以向 SQL 请求获取距离,但这样一来,每对都会有一个新查询,并且 id 列表可以更长(目前最多 50 个元素),我不认为这是一个好方法。

我是 SQL 的新手,但我相信有一些更简单的方法,可以完美地通过一个查询获取所有内容

最佳答案

您可以像这样在单个查询中获取对:

with points(point_from, point_to, distance) as (
values
(1, 2, 15),
(1, 3, 20),
(1, 4, 2),
(3, 2, 16),
(4, 2, 48),
(5, 2, 12),
(3, 4, 19),
(3, 5, 55),
(4, 1, 68),
(4, 5, 18)
)

select least(point_from, point_to) as "from", greatest(point_from, point_to) as "to", distance
from points
where point_from in (1, 2, 4) and point_to in (1, 2, 4)

from | to | distance
------+----+----------
1 | 2 | 15
1 | 4 | 2
2 | 4 | 48
1 | 4 | 68
(4 rows)

There is always only one distance for specific pair of points.

嗯,我不这么认为。

关于python - 从 sql 表中选择值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55422578/

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