Skip to content
Advertisement

Reuse select aliases in MySQL

I currently have a query where I’m doing two subqueries to get X, Y data:

Y is kind of subset of X, since I apply just an additional condition to the existing ones, if X is:

Then Y has an additional AND condition:

And for the value of X I need to take those two results – X and Y and do some calculation. Since I can’t use the aliases, I have to use a subquery, right? But in that case it seems too much.

Is there a way to reuse those subqueries? It seems to be too much of the same.

series_tmp is a temporary table used to create a range of dates with a specific step:

The INNER JOIN used is the only one in the query which is just used to compare against primary/foreign key to further filter by the value of t2.something (t2.something = 1).

The columns I’m using from t1 are just date and some_state, the count is performed using the wildcard.

This is to reproduce the scenario:

The SQLfiddle http://sqlfiddle.com/#!9/45f389.

I’m using MySQL 5.6 so I’m not able to use CTEs 🙁

PS: series_tmp comes from [this].

Advertisement

Answer

You can’t use CTEs in MySQL* but you can use temporary tables which is a close MySQL equivalent (not sure how you calculate Z so I didn’t put that one in):

*prior to version 8 (https://dev.mysql.com/doc/refman/8.0/en/with.html)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement