0

Is there a way to apply a single query across the concatenated rows of multiple tables? I have several tables storing metrics data, where data is initially collected in 10 second intervals, but is periodically rolled up into 1 minute intervals in another table and ultimately into 10 minute intervals in a third table.

That is, I want to be able to do something like:

SELECT value FROM table1 + table2 + table3
  WHERE age(current_timestamp, time) > '2 days'
    AND metrics_name = 'foo';

I don't think a JOIN operation is the right solution here. It looks like I can get the result I want using the UNION operator, which would look something like:

SELECT value from TABLE1 ...
  UNION SELECT value FROM table2 ...
  UNION SELECT value from TABLE3 ...

Where ... is the contents of my WHERE clause (etc), but this gets messy very quickly if the individual SELECT queries are complicated (and fails the "don't repeat yourself" mantra). Is there a different way of cracking this particular nut?

3
  • 2
    using union may be the best option. Commented Dec 5, 2017 at 1:26
  • using union all is possibly an option too, but you don't give us much detail to work with Commented Dec 5, 2017 at 2:17
  • What kind of additional details would help out? I'm trying to avoid having to repeat a query multiple times when selecting across the concatenated results from multiple tables. I was hoping the above was sufficient to illustrate the use case, but I'm happy to work up an extended example if you think that would help. Commented Dec 5, 2017 at 2:20

1 Answer 1

1

Use a nested query with the UNION in the nested quer. And I highly recommend you use UNION ALL unless you want to eliminate duplicates, which you won't in this case, so use UNION ALL.

SELECT
    value
FROM (
    SELECT value, age, metrics_name FROM Table1
    UNION ALL SELECT value age, metrics_name FROM Table2
    UNION ALL SELECT value age, metrics_name FROM Table3
) AS All_Metrics
WHERE
    All_Metrics.age(current_timestamp, time) > '2 days'
    AND All_Metrics.metrics_name = 'foo';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.