如何向 PostgreSQL 子查询添加另一列?
我不太确定如何表达这个问题,所以这里是详细信息。我正在使用一种技巧来计算两个位串之间的汉明距离。查询如下:
select length(replace(x::text,'0',''))
from (
select code # '000111101101001010' as x
from codeTable
) as foo
本质上,它计算两个字符串之间的异或,删除所有 0,然后返回长度。这在功能上相当于两个位串之间的汉明距离。不幸的是,这仅返回汉明距离,而不返回其他值。在codeTable表中,还有一个名为person_id的列。我希望能够返回最小汉明距离以及与之相关的 id。返回最小汉明距离非常简单,只需在“长度”部分添加一个 min() 即可。
select min(length(replace(x::text,'0','')))
from (
select code # '000111101101001010' as x
from codeTable
) as foo
这很好,但是,它只返回汉明距离,而不返回 person_id。我不知道需要做什么才能返回与该汉明距离相关的 person_id。
有人知道如何做到这一点吗?
I wasn't too sure how to phrase this question, so here are the details. I'm using a trick to compute the hamming distance between two bitstrings. Here's the query:
select length(replace(x::text,'0',''))
from (
select code # '000111101101001010' as x
from codeTable
) as foo
Essentially it computes the xor between the two strings, removes all 0's, then returns the length. This is functionally equivalent to the hamming distance between two bitstrings. Unfortunately, this only returns the hamming distance, and nothing else. In the codeTable table, there is also a column called person_id. I want to be able to return the minimum hamming distance and the id associated with that. Returning the minimum hamming distance is simple enough, just add a min() around the 'length' part.
select min(length(replace(x::text,'0','')))
from (
select code # '000111101101001010' as x
from codeTable
) as foo
This is fine, however, it only returns the hamming distance, not the person_id. I have no idea what I would need to do to return the person_id associated with that hamming distance.
Does anybody have any idea on how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我错过了什么吗?为什么要子查询?在我看来,以下内容应该有效:
从那里我得到:
我用 order by 和 limit 1 替换了 min ,因为没有直接的方法来获取 min 函数返回的值的相应 person_id 。一般来说,postgres 足够聪明,不会对整个中间结果进行排序,而只是扫描它必须返回的最低值的行。
Am I missing something? Why the subquery? Looks to me like the following should work to:
Going from there I get:
I replaced the min with an order by and limit 1 because there is no direct way of getting the corresponding person_id for the value returned by the min function. In general postgres will be smart enough not to sort the whole intermediate result but just scan it for the row with the lowest value it has to return.