Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Join two tables without Relations

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?

like image 448
Luis Lavieri Avatar asked Jul 30 '13 17:07

Luis Lavieri


People also ask

Can we join two tables without any relation?

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.

Can two tables be join without primary foreign key relation?

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.

Can we join two tables without on clause?

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.


1 Answers

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;
like image 121
letiagoalves Avatar answered Sep 20 '22 01:09

letiagoalves