I am developing a small application in C++ and using PostgreSQL as back-end database. Along with other tables in my database in have a "projects"
table. Based on each primary key of this table a new table is dynamically added in my Database.
Example:
Suppose the projects table contains following 3 rows:
--------------------------------
| Id |Other Columns Goes here |
--------------------------------
| 1 | |
--------------------------------
| 2 | |
--------------------------------
| 3 | |
--------------------------------
So in this case i also have following three more table
Table1
, Table2
, Table3
Now you might notice that the table names are generated by appending projects.Id at the end of fixed string i.e "Table
".
It might also be possible that for some projects no table is generated.
Example:
Suppose the projects table contains following 3 rows:
--------------------------------
| Id |Other Columns Goes here |
--------------------------------
| 1 | |
--------------------------------
| 2 | |
--------------------------------
| 3 | |
--------------------------------
So in this i might found only following two tables in my database:
Table1
, Table3
Now i simply need to get all the valid projects. For this currently i am using following algo:
//part1
SELECT * FROM Projects Table
get the projects info one by one from the results of above query and store them in new instance of my Custom Class Project
Store the above instance in some contianer e.g Vector say vProjects
//part 2
For each Project p in vProject
if (TableExist(p.Id))
Store p in a new container say vValidatedProjects
Note: The TableExist() method execute the following query:
SELECT COUNT(*) FROM pg_tables WHERE tablename = 'Table"+ p.Id + "'"
Now every thing is working fine as expected but !!! the program executes very slow just because of the second part of above algo, if we have one thousand projects the TableExist() method is also called thousand time and each time this method is called a new query is executed which slow downs the program :(
The solution in my mind is some such thing
//part1
SELECT * FROM Projects Table
WHERE a table exist angainst projets.Id
get only those projects info for whom a dynamic table exist. From the results of above query and store them in new instance of my Custom Class Project
Store the above instance in some contianer e.g Vector say vProjects.
Now in this way only one query did the job for us rather than N+1 Queries (Where N is no of rows in Projects Table) But i don't know how do i write such a query that returns the above results. Please help me in acheiving this.