I have a SQL query in which I only want certain conditions checked if an external condition is met—i.e. if a variable matches a specific value, which is set outside the query (part of a Ruby program).
For example, in a database of book info, I have a variable "author" that is populated with a person's name, or "None". I am comparing this book's values with other books, and would want that variable funneled into the SQL query so that if author = 'None'
, a specified condition is checked. If it is anything other than 'None', the condition can be ignored. Something that would theoretically work like this:
SELECT *
FROM db AS data
WHERE 1=1
AND data.random_field <> '123' if #{author} <> 'None'
I tried this:
AND NOT (#{author} = 'None' AND data.random_field <> '123')
which obviously doesn't work, because the value of the author
variable is interpreted as a field name and not just a variable.
My other thought was to instead get the original author
value from a subquery instead of as an outside variable (since the data is originating from the same database). Something like:
SELECT DISTINCT author
FROM db AS data
WHERE 1=1
AND data.id = '[original_book_id]'
then saving that within the query itself as the author
variable. I'm not sure which of the two options is doable, or better—inserting the outside variable into the SQL query, or setting the variable within the query and then somehow creating the condition based on that value?