jeudi 4 juin 2020

Conditional filtering with user declared variable in MySQL

So, I have a code in Python that filters a dataframe like that: it gets a list of values (they can be 0, 1 or 2) and filter each column of the dataframe based on one of the values of the list (the first column corresponds to the first value of the list, the second column corresponds to the second value of the list...). When the value is 2, it does nothing. When the value is 1 or 0, it gets only the elements of the dataframe that have this value assigned. I do this several times, one for each column, and then get the final result as one dataframe. The thing is that now I'm trying to do the same using MySQL, and I can't figure out a way to do that. The variables will be declared by my at the beginning of the code, so my problem is how to do that conditional filtering. I'll post my Python code below. Does anyone knows what can I do?

if variaveis_mercado["VARIAVEL 1"] != 2:
    matriz_filtrada_1 = matriz_filtrar[
(matriz_filtrar["VARIAVEL 1"] == variaveis_mercado["VARIAVEL 1"]) & (matriz_filtrar["VARIAVEL 2"] == variaveis_mercado["VARIAVEL 2"])]
else: 
    matriz_filtrada_1 = matriz_filtrar

if variaveis_mercado["VARIAVEL 3"] != 2:
    matriz_filtrada_2 = matriz_filtrada_1[(matriz_filtrar["VARIAVEL 3"] == variaveis_mercado["VARIAVEL 3"]) & (matriz_filtrada_1["VARIAVEL 4"] == variaveis_mercado["VARIAVEL 4"])]
else:
    matriz_filtrada_2 = matriz_filtrada_1 

if variaveis_mercado["VARIAVEL 5"] != 2:
    matriz_filtrada_3 = matriz_filtrada_2[(matriz_filtrada_2["VARIAVEL 5"] == variaveis_mercado["VARIAVEL 5"]) & (matriz_filtrada_2["VARIAVEL 6"] == variaveis_mercado["VARIAVEL 6"])]
else:
    matriz_filtrada_3 = matriz_filtrada_2

if variaveis_mercado["VARIAVEL 7"] != 2:
    matriz_filtrada = matriz_filtrada_3[(matriz_filtrada_3["VARIAVEL 7"] == variaveis_mercado["VARIAVEL 7"]) & (matriz_filtrada_3["VARIAVEL 8"] == variaveis_mercado["VARIAVEL 8"])]
else:
    matriz_filtrada = matriz_filtrada_3

OBS: I was thinking about something like: if @variable = 2 then select * else filter.

Aucun commentaire:

Enregistrer un commentaire