简体   繁体   English

postgres-保留查询中的重复项

[英]postgres - retain duplicates from query

I just ran into a bug in our code based on the way we're matching data against a Postgres array. 基于我们将数据与Postgres数组匹配的方式,我刚在代码中遇到一个错误。

Here's the issue: 这是问题所在:

In the database, we have a surcharge column that lives in the appointment table where the ids of all surcharges attached to an appointment are stored. 在数据库中,我们有一个surcharge列,该列位于appointment表中,其中存储了附加到约会的所有附加费的ID。 In some cases, a surcharge may be added twice and therefore would look like {1,1} in the database. 在某些情况下,附加费可能会增加两次,因此在数据库中看起来像{1,1}

I was using a simple query like the following to retrieve the surcharge data associated with the surcharges that have been attached to the appointment: 我正在使用类似以下的简单查询来检索与已附加到约会的附加费相关联的附加费数据:

SELECT s.* FROM surcharge s, appointment a WHERE s.id = ANY(a.surcharges);

Unfortunately, I didn't test this case where more than one of the same surcharge exists. 不幸的是,我没有测试这种情况,其中存在多个相同的附加费。 The result is that only 1 record is being returned rather than the 2 I really need. 结果是只返回了1条记录,而不是我真正需要的2条记录。

To clarify, an example would be an appointment with appointment.surcharges = {1,1} , I'd actually want to be able to retrieve the record from surcharges TWICE because it has two surcharges associated with it. 为了阐明这一点,一个示例是带有约会的appointment.surcharges = {1,1} ,我实际上希望能够从surcharges TWICE中检索记录,因为它有两个与之相关的附加费用。 I then use those records to create billing-related transactions associated with the appointment. 然后,我使用这些记录来创建与约会相关的与计费相关的交易。

All that said, is there a simple way to allow a query to return the duplicates that I need? 所有这些,有没有一种简单的方法允许查询返回我需要的重复项?

I can handle this situation in code, but it would be great to run a simple query to handle this situation. 我可以在代码中处理这种情况,但是最好运行一个简单的查询来处理这种情况。

I'm running Postgres 9.5. 我正在运行Postgres 9.5。

Thank you in advance! 先感谢您!

I think a plain inner join to an unnested table of surcharges should give you what you want: 我认为,简单地将内部加入未加附加费的表格应会给您您想要的东西:

SELECT s.*
FROM surcharge s
INNER JOIN
(
    SELECT UNNEST(surcharges) AS surcharges
    FROM appointment
) a
    ON s.id = a.surcharges;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM