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
  • 34,265
  • 92
  • 284
  • 515

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
  • 44,205
  • 11
  • 83
  • 107
  • 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
  • 63,861
  • 10
  • 90
  • 118
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,306
  • 1
  • 14
  • 28