I think your practice is fine. Here are the two queries and their explain results:
explain extended SELECT
w,
x,
y,
(w + x) / y as z
FROM
(SELECT
(SELECT SUM(s) FROM test2) as w,
a + b as x,
a - b as y
FROM
test) somealias;
+----+-------------+------------+------+---------------+------+---------+------+------+----------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+------------+------+---------------+------+---------+------+------+----------+-------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |
| 2 | DERIVED | test | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |
| 3 | SUBQUERY | test2 | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |
+----+-------------+------------+------+---------------+------+---------+------+------+----------+-------+
explain extended SELECT
(SELECT SUM(s) FROM test2) as w,
a + b as x,
a - b as y,
((SELECT SUM(s) FROM test2) + (a + b)) / (a -b) as z
FROM
test
+----+-------------+-------+------+---------------+------+---------+------+------+----------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+----------+-------+
| 1 | PRIMARY | test | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |
| 3 | SUBQUERY | test2 | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |
| 2 | SUBQUERY | test2 | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |
+----+-------------+-------+------+---------------+------+---------+------+------+----------+-------+
If I'm right the second version runs the complex (maybe bottleneck) subquery on table test2
twice, so it should be slower than the first query which runs the complex subquery only once. Furthermore, the first one is much easier to read. So, I prefer the first one. (I'm not a MySQL guru, feel free to correct me.)
SELECT (a+b) / (a-b) AS z FROM basetable
? \$\endgroup\$x
andy
in the outer query. Hopefully that clarifies the problem. \$\endgroup\$x
,y
, andz
? That you can't add, say,ORDER BY z
? (orORDER BY x
if you don't use the subquery?) I believe you canORDER BY a+b
, if that's what you want. \$\endgroup\$x / y
to(a+b)/(a-b)
in the column spec. The alias can't be used there, but (from the MySQL docs) it "can be used in GROUP BY, ORDER BY, or HAVING clauses." Is the problem thata+b
are actually more long/complex? In that case you could define a function. \$\endgroup\$