Skip to content
Advertisement

SQL JOIN to grab multiple tables with no relational criteria

How can I use the SQL JOIN statement to simply grab data from multiple tables based on a WHERE clause rather than ON relational matching criteria?

I just want to grab rows from several tables by date:

So something like:

SELECT * FROM table1, table2, table3 WHERE date > '2020-01-01 00:00:00'

The above wouldn’t work obviously and I think a JOIN statement is in order but I’m not sure how to implement since I’m not looking to match data between the tables as would be the case with the ON directive.

To put it another way, I’m looking to replace the following 3 statements..

SELECT * FROM table1 WHERE date > '2020-01-01 00:00:00'

SELECT * FROM table2 WHERE date > '2020-01-01 00:00:00'

SELECT * FROM table3 WHERE date > '2020-01-01 00:00:00'

..with just a single statement.

Advertisement

Answer

JOIN is not for your situation. You should use UNION instead. The only thing you should remember number of columns you select should be same for each select. Here s example https://dev.mysql.com/doc/refman/8.0/en/union.html:

SELECT * FROM t1 UNION SELECT * FROM t2;

In your situation it will be

SELECT * FROM table1 WHERE date > '2020-01-01 00:00:00' UNION

SELECT * FROM table2 WHERE date > '2020-01-01 00:00:00' UNION

SELECT * FROM table3 WHERE date > '2020-01-01 00:00:00';
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement