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 '%addr@yahoo.com%'
OR phones LIKE '%addr@yahoo.com%'
AND history !='None'

This is producing 2 records:

INSERT INTO `mytable` (`id`, `emails`, `phones`, `history`) VALUES
(118, 'PLEASE SET', NULL, 0, 'addr@yahoo.com', NULL, 0, 'None'),
(237, 'PLEASE SET', NULL, 0, 'addr@yahoo.com', NULL, 0, 'gomez');

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

user1592380
  • 30,233
  • 76
  • 247
  • 468

3 Answers3

2

You should explicitly set parenthesis in your WHERE clause :

WHERE (all_emails LIKE '%addr@yahoo.com%'
   OR all_phones LIKE '%addr@yahoo.com%')
  AND history !='None'
potashin
  • 43,297
  • 11
  • 81
  • 105
  • Thank you very much! Why does The parentheses help? – user1592380 Jan 12 '15 at 21:23
  • @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. – potashin Jan 12 '15 at 21:26
2

Organize your OR criteria in ()

SELECT *
FROM mytable
WHERE (all_emails LIKE '%addr@yahoo.com%'
OR all_phones LIKE '%addr@yahoo.com%')
AND history !='None

Sample Demo

M Khalid Junaid
  • 62,293
  • 9
  • 87
  • 115
0
SELECT *
FROM mytable
WHERE (all_emails LIKE '%addr@yahoo.com%'
OR all_phones LIKE '%addr@yahoo.com%')
AND history NOT IN(
SELECT history FROM mytable WHERE history LIKE 'None')
Ali Mohammadi
  • 1,294
  • 1
  • 13
  • 28