I am trying to select data from two tables. The DBA has the tables configured in such a way that the first table spools records for 5 minutes, and then a procedure moves the data to the second table and cleans the spool. This repeats constantly. The issue is I need to select data from both tables.
Here is my query so far:
select * from table1,table2
where ( (table1.field>=DATE_SUB(UTC_TIMESTAMP(), INTERVAL 5 MINUTE))
OR
(table2.field>=DATE_SUB(UTC_TIMESTAMP(), INTERVAL 5 MINUTE)) )
Searching for either of the conditions individually works quickly, however when I put them together like above, the system just sits there and becomes unresponsive. I’m just curious what I’m doing wrong. Should I do this with a union instead?
You are joining 2 tables without any joining where clause, so you are pulling in M*N records (a Cartesian product).
In other words, if table1 has 100 records matching the first condition, and table2 has 10,000 records, you are retrieving 1,000,000 records instead of 10,100. To top that off, every record you are retrieving is 2x the size since it includes all the fields from the row of table1 + all the fields from the row of table2, so not only are you increasing the amount of rows by 100x (using my example #s), you are also increasing the retrieved data size by 200x.
What you want is to use a UNION instead of a join.