3

I am having trouble selecting rows in MySQL. I do not want some rows to be selected, but they are being selected.

My query:

SELECT  name,url
    FROM  additions
    WHERE  enabled = 1
      AND  picture = 1
      AND  name LIKE '%value%'
      OR  tags LIKE '%value%'
      OR  subtext LIKE '%value%';

I do not want the rows that do not have a picture (picture = 0) and also rows that are not enabled (enabled = 0) to be selected. I think the rows match because either the name, tags and/or subtext matches the value, because of the OR condition in WHERE clause.

I want only the rows to be selected that have a picture and are enabled, regardless of the match in name, tags, subtext. How can I achieve that?

| improve this question | | | | |
6

The answer: as ypercube said, the solution is:

adding parentheses around the OR conditions

like so:

SELECT name,url FROM additions WHERE enabled = 1 AND picture = 1 AND (name LIKE '%value%' OR tags LIKE '%value%' OR subtext LIKE '%value%');

With the parentheses, AND will take precedence and the entire section in the LIKE value comparison will have to be true together with the other evaluations, like enabled = 1 and picture = 1. Without the parentheses the OR statements are evaluated individually (and if one of them happens to be true, a row will be selected).

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.