I have a query (PostgreSQL 15.4) like this:
Select p."prodId", p."prodDesc", p."areaName", x."location1" as "Location"
From ops."Products" p
Inner Join ops."Locations" x on p."prodId" = x."prodId"
and p."areaName" = x."areaName1"
Here’s the caveat: in the table Locations
, there are three locations, location1
, location2
, and location3
. In addition, there are three columns areaName1
, areaName2
, and areaName3
.
I need to return the location
column as either location1
, location2
, or location3
, based on the column areaName
in the Products
table being equal to one of the corresponding areaName
columns in Locations
: areaName1
, areaName2
, or areaName3
.
My thinking was to be able to use some sort of function where I could join
the function to the rest of my query and have the function handle all of the above. In a land and time far away, I probably would’ve handled this as dynamic SQL, but wondering if there is a better way to go?
2
Answers
You should change the locations table. Don’t have the three (areaname, location) pairs in one row, have them in three rows.
You can do that inline in the query, but it will be slower (and less maintainable) than just fixing the data structure.
You can use a
case
to switch between them and anin
/=any(array[])
to join on any one.demo at db-fiddle