I am new in PostgreSQL and I wonder if it's possible to use number
from table tbc
as part of the table name in left join 'pa' || number
. So for example if number is 456887 I want left join with table pa456887. Something like this:
SELECT tdc.cpa, substring(tdc.ku,'[0-9]+') AS number, paTab.vym
FROM public."table_data_C" AS tdc
LEFT JOIN concat('pa' || number) AS paTab ON (paTab.cpa = tdc.cpa)
And I want to use only PostgreSQL, not additional code in PHP for example.
Either way, you need dynamic SQL.
Table name as given parameter
Call:
Generally, you would sanitize table names with
format ( %I )
to avoid SQL injection. With just aninteger
as dynamic input that's not necessary. More details and links in this related answer:INSERT with dynamic table name in trigger function
Data model
There may be good reasons for the data model. Like partitioning / sharding or separate privileges ...
If you don't have such a good reason, consider consolidating multiple tables with identical schema into one and add the
number
as column. Then you don't need dynamic SQL.Consider inheritance. Then you can add a condition on
tableoid
to only retrieve rows from a given child table:Be aware of limitations for inheritance, though. Related answers:
Name of 2nd table depending on value in 1st table
Deriving the name of the join table from values in the first table dynamically complicates things.
For only a few tables
LEFT JOIN
each ontableoid
. There is only one match per row, so useCOALESCE
.For many tables
Combine a loop with dynamic queries: