I’m trying to do some dynamic variable calculations on a select and reference those variables in the where statement. After searching the following is as close as I’ve been able to get thanks to Jonas’s post here MySQL user-defined variable in WHERE clause
I’m thinking somethere where the output is address (from the original table, @bitcoin, and @cash_value, instead of using two separate select statements as shown below.
select @address := address, @bitcoin := (value / power(10, 8)), @cash_value := @bitcoin * 43913.7515932587 FROM knownaddresses_bitcoin WHERE address = '111111111111111111112czxoHN';
select @address, @bitcoin, @cash_value where @cash_value > 1;
2
Answers
You’re on the right track with user-defined variables in MySQL. However, MySQL doesn’t allow using aliases for user-defined variables directly in the WHERE clause. You can work around this limitation by using a subquery or a derived table. Here’s an example using a derived table:
This query uses a subquery to calculate bitcoin and cash_value based on the value column from knownaddresses_bitcoin for the specified address. Then, the outer query filters the results based on the cash_value being greater than 1.
Remember to replace ‘111111111111111111112czxoHN’ with the specific address you’re interested in querying.
This way, you avoid using user-defined variables and achieve the desired filtering based on the calculated values in a single SQL statement.
Finally: