Can you do a + or - value operation in a Mysql query?

Asked

Viewed 195 times

4

Example:

select quantidade from tabela where quantidade é mais ou menos = '5';

Does anyone know any way to do this in Mysql? I have an approximate value of 5 and I would like to bring it from the database in a query, only I don’t know any function in SQL or any way to make the condition I want as in the example.

  • 2

    Define what is "more or less".

  • You can use the, greater than, greater equal, less than, less equal ... more or less and whatever you don’t have. Try to explain better where this is applied

  • 1

    A value that could be more than 5 and less than 5 would not be any value? Oo

  • You want to know if it’s any different than five?

3 answers

6

Using the ABS, becomes very simple:

SELECT campos FROM tabela WHERE ABS( valor - 5 ) < .5
                                             │      │
                          valor buscado 5 ───┘      │
  tolerancia 0,5 por exemplo (ajuste como quiser) ──┘

See working on SQL Fiddle.

The ABS( ) returns the always positive value, so what is after the < serves to adjust the tolerance either for more or for less.

  • 2

    Much more elegant than my answer. Have an upvote good sir.

5

The logic of "marromeno" can be made with an auxiliary variable of variation.

DECLARE @marromeno DECIMAL(0,2)
DECLARE @eixoDaGrampola DECIMAL(2,2)

-- atribua valores aqui

SELECT
    *
FROM
    inmetro
WHERE
    valor BETWEEN (@eixoDaGrampola - @marromeno) and (@eixoDaGrampola + @marromeno)

For example, if your variation is 0.2 more or less... If you give the values of 5 to @eixoDaGrampola and 0.2 to @marromeno, you will get all values between 4.8 and 5.2.

Good luck.

  • Exactly... you have to give a margin value.

  • I left another version, but yours is a good solution too. + 1

  • @Bacco yours is stronger because it has ABS

  • 1

    Yeah, if it works well with ABS the result is positive :)

0

select quantity from table Where quantity != '5';

Resolves?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.