Is there a way to reuse a calculated field within a mysql statement. I get the error "unknown column total_sale" for:
SELECT
s.f1 + s.f2 as total_sale,
s.f1 / total_sale as f1_percent
FROM sales s
or do I have to repeat the calculation, which would make for a very long SQL statement if I added all the calculations I need.
SELECT
s.f1 + s.f2 as total_sale,
s.f1 / (s.f1 + s.f2) as f1_percent
FROM sales s
of course I can do all the calculations in my php program.
You can use a sub-select:
You can use subqueries, like this:
Edit:
fixed cartesian product, assuming the primary key is
id
.This should be equivalent to OMG Ponies' solution after optimizing, but I think it will become harder to read if you need more subqueries.
Only cross-platform supported means is by using a derived table/inline view:
The following seems to work well in my testing on MySQL 5.5:
I had a look at various answers here and did a few experiments.
Specifically I am using MariaDB 10.1.
For a "simple" thing you can do what Robert D suggested in his comment:
If you are using some sort of aggregate function with an inner join you can't use this, but you can combine this approach with the inner join approach as follows (NB VAT = "sales tax"... and NB in financial data currency fields typically have 4 decimal places, I think it's historic...)
I wanted to use the above to create a
View
to list invoices with their subtotals, VAT and totals... it turned out that MariaDB (and almost certainly MySQL) don't allow nesting in theFROM
clause. However this is easily solved by making a firstView
which lists theInvoiceNo
andSubtotal
, and then making a secondView
which references the first. Performance-wise I have no idea at all about this sort of double-View
arrangement.Yes, you can reuse variables. This is how you do it:
Read more about it here: http://dev.mysql.com/doc/refman/5.0/en/user-variables.html
[Note: This behavior is undefined. According to the MySQL docs:]