Reputation: 1
In a webpage I want to display several tables with information.
To do that, at the moment I do
SELECT * FROM tableONE WHERE field LIKE 'criteria'
then I process the result in a foreach loop. Then I do another query to the next table and process it again
SELECT * FROM tableTWO WHERE field LIKE 'criteria'
....
SELECT * FROM tableTWENTY WHERE field LIKE 'criteria'
I've the feeling that making 20 connections with the database is suboptimal and I could make a single query and in the foreach loop put each result in the appropriate table. The issues I found to do it are:
There is no related column amongst them, so I can not do a JOIN ON.
If I do a cartesian join I get many redundant rows
I can not use UNION because the columns on each table are different.
What is the most efficient way to do this? Thanks
I've tried JOIN, UNION and separating the tables with comas (cartesian join), but they don't give the expected result
Upvotes: 0
Views: 109
Reputation: 381
Just use UNION Clause
SELECT field1, field2, filed3 FROM table1
UNION
SELECT field1, NULL as filed2, field4 as filed3 FROM table2
;
Beware that
SELECT
statement within UNION
must have the same number of columnsUpvotes: 1