问题
I have some variables in bash like below.
min_date='2020-06-06'
max_date='2020-06-08'
max_seq_min_date=1 --This is till where data is processed
max_seq_max_date=3 --This is till where data has to be processed
batch_date is the column where I will use the min and max_date values
For each date there will be 4 sequences
I want to generate a where clause that I can use in sql query
Now I want to generate a where clause that looks like below
WHERE 1=1 or (batch_date = '2020-06-06' and seq_num in ('2','3', '4'))
or (batch_date = '2020-06-07' and seq_num in ('1','2','3','4'))
or (batch_date = '2020-06-08' and seq_num in ('1','2','3'))
How can i achieve what I want?
回答1:
It will be more efficient to make minor changes to the query - making it easier to generate (equivalent) SQL dynamically.
It uses "between" operator to avoid variable length lists for the 'in (...)' conditions.
Note comment about 1=1, it is kept as per question, but need to be reviewed, as it will always make the condition pass.
min_date='2020-06-06'
max_date='2020-06-08'
max_seq_min_date=1
max_seq_max_date=3
echo "
WHERE 1 = 1 or case
when batch_date = '$min_date' then seq_num between 1 and $max_seq_min_date
when batch_date = '$max_date' then seq_num between 1 and $max_seq_max_date
when batch_date between '$min_date' and '$max_date' then seq_num between 1 and 4
else false
end
"
I do NOT have mysql, but the above works for Postgresql.
回答2:
Just use interpolation, i.e.
sql_clause="... batch_date = '$min_date' and seq_num in ('2','3', '4') ...."
来源:https://stackoverflow.com/questions/62292634/generate-where-clause-in-bash-using-variables