1

I want to edit my existing mySQL query based on whether the column show_only_on has a value or not.

If it has a value, then the correct query is the below

Select *
FROM alerts_data
WHERE id = 'abc' AND running_status='idle'
AND FIND_IN_SET("https://www.example.com/pricing", show_only_on)

And if it does not have a value, I just leave out the

AND FIND_IN_SET("https://www.example.com/pricing", show_only_on)

or make the FIND_IN_SET return true.

How can I do this using only this query and not any PHP ?

2

3 Answers 3

3

How about running it through an OR/AND statement?:

Select *
FROM alerts_data
WHERE id = 'abc' AND running_status='idle'
AND (
  show_only_on IS NULL /* Whatever check you do to ensure it's not set */
  OR FIND_IN_SET("https://www.example.com/pricing", show_only_on)
)
Sign up to request clarification or add additional context in comments.

Comments

2

If I understand you correctly, you want to return all records where wither show_only_on is NULL or where show_only_on matches the FIND_IN_SET logic?

Sounds like this:

WHERE
    id = 'abc' AND
    running_status='idle' AND
    (
        FIND_IN_SET("https://www.example.com/pricing", show_only_on) OR
        show_only_on IS NULL
    )

Comments

0

Another option, one that I tend to use in parameterised queries:

WHERE id = 'abc'
AND running_status='idle'
AND COALESCE(show_only_on, "https://www.example.com/pricing") = "https://www.example.com/pricing"

Parameterised:

WHERE id = 'abc'
AND running_status = 'idle'
AND COALESCE(show_only_on, :url) = :url

Note this only works where show_only_on is NULL if and only if the value is considered empty/missing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.