I have different tables with the same structure, and I would like to join them by one of their columns.
The problem is that they don't share information in that column.
Table 1 - Type A:
Name | Value
Table 2 - Type B:
Name | Value
Resulting table:
(In a single column)
nameFromA
nameFromB
...
So far, I have tried:
SELECT TABLE1.NAME, TABLE2.NAME
FROM TABLE1, TABLE2
WHERE TABLE1.NAME = 'SearchQuery'
OR TABLE2.NAME = 'SearchQuery' LIMIT 2;
I know that my query is wrong because I'm calling more columns that what I want, but I am not sure how to join everything in a single column. How can I accomplish this?
The answer to this question is yes, you can join two unrelated tables in SQL, and in fact, there are multiple ways to do this, particularly in the Microsoft SQL Server database. The most common way to join two unrelated tables is by using CROSS join, which produces a cartesian product of two tables.
A primary key is not required. A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.
Any JOIN without an ON clause is a CROSS JOIN. The LEFT JOIN is an outer join, which produces a result set with all rows from the table on the "left" (t1); the values for the columns in the other table (t2) depend on whether or not a match was found.
Have you tried?
SELECT TABLE1.NAME
FROM TABLE1
WHERE TABLE1.NAME = 'SearchQuery'
UNION
SELECT TABLE2.NAME
FROM TABLE2
WHERE TABLE2.NAME = 'SearchQuery';
You may want to use UNION ALL
if you don't want to exclude repeated values.
To limit your result set you can do something like this:
SELECT * FROM ( HERE GOES ABOVE QUERY ) LIMIT 2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With