Bahrami-Reza
Bahrami-Reza

Reputation: 608

mysql where clause dosnt work

i have this MySQL query to retrieve some data just for those who have language = 3

  SELECT
  noor_content.id,noor_content.body,noor_content.category,noor_content.introtext,noor_content.title,noor_content.keywords,noor_content.language,path 
  FROM (`noor_content`) 
  join noor_categories 
  on (noor_content.category = noor_categories.id) 
  WHERE `language` = '3' 
  AND noor_content.keywords LIKE '%سمنگان%' 
  or noor_content.keywords LIKE '%جوزجان%' 
  or noor_content.keywords LIKE '%سرپل%' 

Problem: the query retrieved those data that have another language but i mentioned language='3'

Screenshot:

enter image description here

Upvotes: 2

Views: 72

Answers (5)

Tamil Selvan C
Tamil Selvan C

Reputation: 20199

Use bracket for search keywords

SELECT noor_content.id,noor_content.body,noor_content.category,noor_content.introtext,noor_content.title,noor_content.keywords,noor_content.language,path 
  FROM `noor_content` 
  join noor_categories 
  on noor_content.category = noor_categories.id
WHERE language = 3 AND 
(noor_content.keywords LIKE '%سمنگان%' or 
noor_content.keywords LIKE '%جوزجان%' 
or noor_content.keywords LIKE '%سرپل%')

Upvotes: 0

Rakesh Patel
Rakesh Patel

Reputation: 70

Because you are using OR operator between conditions so use Brackets() 
like this then try

WHERE `language` = '3' 
AND ( noor_content.keywords LIKE '%سمنگان%' 
OR noor_content.keywords LIKE '%جوزجان%'  
OR noor_content.keywords LIKE '%سرپل%' )

Upvotes: 0

JayKandari
JayKandari

Reputation: 1248

put conditions in brackets.

 SELECT noor_content.id,noor_content.body,noor_content.category,noor_content.introtext,noor_content.title,noor_content.keywords,noor_content.language,path 
  FROM (`noor_content`) 
  join noor_categories 
  on (noor_content.category = noor_categories.id) 
  WHERE (`language` = '3' )
  AND ((noor_content.keywords LIKE '%سمنگان%') 
  or (noor_content.keywords LIKE '%جوزجان%') 
  or (noor_content.keywords LIKE '%سرپل%' ));

Upvotes: 0

Barmar
Barmar

Reputation: 780879

It's because AND has higher precedence than OR, so your WHERE clause is being interpreted as:

WHERE (language = 3 AND noor_content.keywords LIKE '%سمنگان%')
OR noor_content.keywords LIKE '%جوزجان%' 
OR noor_content.keywords LIKE '%سرپل%'

The language test is only combined with the first LIKE, not the others. You need to add parentheses:

WHERE language = 3 
AND (noor_content.keywords LIKE '%سمنگان%'
    OR noor_content.keywords LIKE '%جوزجان%' 
    OR noor_content.keywords LIKE '%سرپل%')

Upvotes: 1

Sadikhasan
Sadikhasan

Reputation: 18600

You have to put bracket for AND and ORcondition to satisfy your condition like below

 WHERE `language` = '3' 
  AND (noor_content.keywords LIKE '%سمنگان%' 
  or noor_content.keywords LIKE '%جوزجان%' 
  or noor_content.keywords LIKE '%سرپل%' );

Upvotes: 2

Related Questions