Join multiple unrelated tables in MySQL

I have a website that stores the parameters <select>in several tables and extracts all the relevant ones depending on the individual page. At the moment I finish the query as follows: SELECT foo FROM foo_tbl;SELECT bar FROM bar_tbl;etc. This is not a very bad problem, but I have to iterate over each selection result separately.

I would like to extract all of them into one grid, then do something like

if $row['foo'] != NULL { add to the foo options }
if $row['bar'] != NULL { add to the bar options }
etc

If I use a query such as SELECT DISTINCT f.foo, b.bar FROM foo_tbl AS f, bar_tbl AS b, I include all possible string combinations (first first line foo, first line foo second, second first line foo, second second line foo, etc. etc.).

Is there a way to make such a choice and have only one instance of each element in the column and fill the remaining rows in the column with zeros?

+3
source share
3 answers

You can do something like the following: Assuming table foo has columns a, b, c and table bar has columns d, e, f

Select 'isFOO', a, b, c, null, null, null from foo
Union All
Select 'isBAR',null, null, null, d, e, f from bar
+8
source

Do you consider using a union

select foo as "f1" from footable where ..whatever..
union
select bar as "f1" from bartable where ..whatever..

this will give you one set of results .. but if the tables are really not related in any way, it still will not help you.

+8
source

, , :

( a, b, c, '1' , ....) UNION ( a, null, null, '2' , ....) UNION ( a, b, null, '3' , ....)

+1

Source: https://habr.com/ru/post/1731316/


All Articles