I just ran into a bug in our code based on the way we're matching data against a Postgres array.
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. In some cases, a surcharge may be added twice and therefore would look like {1,1}
in the database.
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.
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. 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.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.