0

I have the following mysql table (simplified):

CREATE TABLE IF NOT EXISTS `mytable` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`emails` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`phones` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`history` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,

PRIMARY KEY (`id`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=259 ;

I have the following query :

SELECT *
FROM mytable
WHERE emails LIKE '%[email protected]%'
OR phones LIKE '%[email protected]%'
AND history !='None'

This is producing 2 records:

INSERT INTO `mytable` (`id`, `emails`, `phones`, `history`) VALUES
(118, 'PLEASE SET', NULL, 0, '[email protected]', NULL, 0, 'None'),
(237, 'PLEASE SET', NULL, 0, '[email protected]', NULL, 0, 'gomez');

but I was expecting the one with history = 'None' not to be included. What am I doing wrong?

3
  • I think the different operator in MySQL is <> and not != Commented Jan 12, 2015 at 21:05
  • 2
    Put parentheses around your OR conditions. Commented Jan 12, 2015 at 21:05
  • 2
    @MarcoAurélioDeleu: Both != and <> are "not equals" in MySQL. Commented Jan 12, 2015 at 21:07

3 Answers 3

2

Organize your OR criteria in ()

SELECT *
FROM mytable
WHERE (all_emails LIKE '%[email protected]%'
OR all_phones LIKE '%[email protected]%')
AND history !='None

Sample Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! Why does The parentheses help?
@user61629 its regarding operator precedence for full overview checkout this question and answer stackoverflow.com/questions/1241142/…
2

You should explicitly set parenthesis in your WHERE clause :

WHERE (all_emails LIKE '%[email protected]%'
   OR all_phones LIKE '%[email protected]%')
  AND history !='None'

2 Comments

Thank you very much! Why does The parentheses help?
@user61629 : You are welcome.AND has a precedence over OR as a logical operator, parenthesis helps to avoid cases like you did have, when at first was evaluated AND and only then OR, which wasn't what you've wanted to achieve in the first place.
0
SELECT *
FROM mytable
WHERE (all_emails LIKE '%[email protected]%'
OR all_phones LIKE '%[email protected]%')
AND history NOT IN(
SELECT history FROM mytable WHERE history LIKE 'None')

2 Comments

Test Again (I Changed)!
You still don't need the subquery.

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.