mysql calculation field stored in another field - mysql

I have fields in mysql that look like this:
constant1 , constant2, variable1, variable2, formula
The formula field stores a formula utilizing constant1, constant2, variable1 and variable2.
For example, the formula field may contain a calculation like this:
constant1 * variable1
When I use a select statement like this:
SELECT constant1, constant2, variable1, variable2, formula
FROM table
How do I retrieve the calculation result of constant1 * variable1 based on formula field?

You need one of two approaches:
Call some sort of eval function on your formula.
Parse the formula into an expression tree, substitute the values and then evaluate the expression.
Usig eval is quick to implement but dangerous because it could do something you didn't expect. Parsing the formula is best done with a dedicated library for building parsers, but if your expression syntax is very simple you could write a parser yourself without using a library. In either case SQL isn't the right language for this.
I'd recommend finding a library that can help you parse the formula. Whichever route you choose though, I'd suggest doing the bulk of the work on the database client, not in SQL. SQL was simply not designed for this sort of task.

Related

MYSQL Best way to parametrize variable values for IN clause in stored procedure

I have to write a stored procedure where I want to set values for a variable called colorId using IN operator, the parameter can be a list of integer ids or no ids. I am wondering what should be the type of variable in the stored procedure?
where color_id IN (1,2,3,4);
Thanks for the help!
If you send a string like '1,2,3,4' as a single parameter, the query will run as if you had done this:
where color_id IN ('1,2,3,4');
The way MySQL does implicit type casts to integer, this converts the value to an integer using only the leading digits, and ignores everything after the first comma. So it will really run as if you had done this:
where color_id IN (1);
There is no way to "remove" the quotes. The point of query parameters is that they are not combined with the query until after the SQL parsing is done. Therefore the parameter is fixed as a single string value in that expression. You can't convert a parameter into a list of discrete values, because that would change the syntax of the query.
So you must pass multiple parameters, one for each value in your list. Like this:
...where color_id IN (?, ?, ?, ?);
And use some function in your client application to split the string into multiple parameters and then pass them not as a single string value, but as multiple integer values.
Some people try to use tricks like using MySQL's FIND_IN_SET() function, but I don't recommend this, because it cannot be optimized with any index.
You tagged this question stored-procedures from which I infer that you are trying to write a procedures that accepts a string of comma-separated integers and use it in an IN() predicate. This is more inconvenient to do in a stored procedure than in any other programming language, because MySQL's stored procedure language doesn't support arrays or good functions for splitting strings or counting elements. It can be done with enough effort, but the code is awful and you will quickly wish you were using any other language.
Your can pass parameter value like this - '1,2,3,4' and FIND_IN_SET function will be able to search in the provided string:
SELECT *
FROM colors
WHERE FIND_IN_SET(color_id, param); # param --> '1,2,3,4'

how to pass a database column as a parameter in a user defined function?

i have a code in sql for string comparison which takes two parameters as input works upon it and returns a result. both of the parameters are words, i want to change the parameter from a single word to a database column. how do i do that?
say for example in java its like storing the data in an array and than passing the whole array. can something like this be done in sql?
You can use the Select query for passing each value of a particular column from the table into your function.
like this,
SELECT compare_city_name('baroda',t.cityname) from tablename as t
In this query, you pass all cities name from cityname column to the function compare_city_name one by one.
Pass it as a VARCHAR, then build the query with "prepare" and "execute" it.

MYSQL REGEXP with JSON array

I have an JSON string stored in the database and I need to SQL COUNT based on the WHERE condition that is in the JSON string. I need it to work on the MYSQL 5.5.
The only solution that I found and could work is to use the REGEXP function in the SQL query.
Here is my JSON string stored in the custom_data column:
{"language_display":["1","2","3"],"quantity":1500,"meta_display:":["1","2","3"]}
https://regex101.com/r/G8gfzj/1
I now need to create a SQL sentence:
SELECT COUNT(..) WHERE custom_data REGEXP '[HELP_HERE]'
The condition that I look for is that the language_display has to be either 1, 2 or 3... or whatever value I will define when I create the SQL sentence.
So far I came here with the REGEX expression, but it does not work:
(?:\"language_display\":\[(?:"1")\])
Where 1 is replaced with the value that I look for. I could in general look also for "1" (with quotes), but it will also be found in the meta_display array, that will have different values.
I am not good with REGEX! Any suggestions?
I used the following regex to get matches on your test string
\"language_display\":\[(:?\"[0-9]\"\,)*?\"3\"(:?\,\"[0-9]\")*?\]
https://regex101.com/ is a free online regex tester, it seems to work great. Start small and work big.
Sorry it doesn't work for you. It must be failing on the non greedy '*?' perhaps try without the '?'
Have a look at how to serialize this data, with an eye to serializing the language display fields.
How to store a list in a column of a database table
Even if you were to get your idea working it will be slow as fvck. Better off to process through each row once and generate something more easily searched via sql. Even a field containing the comma separated list would be better.

Format Text Field To Date In Access Query

I have a form in Access that has two text boxes that are format to be a short date. I am now attempting to capture those values and use in a query in the WHERE clause. I tried this syntax
Between CDate([Forms]![Form1]![date1]) And CDate([Forms]![Form1]![date2])
This expression is typed incorrectly, or it is to complex to be evaluated. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning parts of the expression to variables.
How should I capture & convert the entries from my form text boxes so that I can use them in my query?
Specify the parameters to free Access from guessing, then use these "as is":
Parameters
[Forms]![Form1]![date1] DateTime,
[Forms]![Form1]![date2] DateTime;
Select
<your select statement>
From
<your table/query>
Where
[YourDateField] Between
[Forms]![Form1]![date1] And
[Forms]![Form1]![date2]

Condition-check function in SQL SELECT (MySQL)?

I use MySQL and need to output in SQL SELECT a result of a function that is not uniform.
Namely,
if column A value is below certain number, I need to output one algebraic correction to column B inside the SELECT statement
and if it is above, another.
The algebraic corrections are not guaranteed to be "smooth" so I ought to have some IF-like statements.
I would like to do all these inline without e.g. creating custom functions. This is easier to maintain.
What would be the best syntax to achieve this "step" correction inside SELECT?
I think you can achieve this using a CASE expression. Something like this:
SELECT *,
CASE WHEN A < threshhold THEN exp_1(B) ELSE exp_2(B) END AS some_col,
FROM yourTable
Here you would replace exp_1(B) and exp_2(B) with the actual expressions involving column B.