lone
lone

Reputation: 5

MySQL WHERE and Like Question

Is there a way I can combine the multiple WHERE's into one

Here is what I want to combine.

SELECT * 
FROM question 
WHERE content LIKE '%$search_each%'
WHERE title LIKE '%$search_each%'
WHERE summary LIKE '%$search_each%'

Upvotes: 0

Views: 4361

Answers (2)

QuinnG
QuinnG

Reputation: 6424

SELECT * 
FROM question 
WHERE content LIKE '%$search_each%'
AND title LIKE '%$search_each%'
AND summary LIKE '%$search_each%'

This will only return entries where the content, title and summary contain the search text.

SELECT * 
FROM question 
WHERE content LIKE '%$search_each%'
OR title LIKE '%$search_each%'
OR summary LIKE '%$search_each%'

This will return entries any of the fields contain the search term.

For example: Let's assume you have the following data in the order of content, title, summary my title, my summary, my content this is a title, this is not a title, neither is this Not a fan, of typing a lot, so I'm a stopping now

If search_each is set to "title" and you use the AND query, you would only get back the first row. The second row wouldn't come back because the summary [3rd item] does not have the word title in it. If you have the same search_each and use the OR query both 1 and 2 will come back. Both of them contain the search term in at least 1 of the three columns. If you set the search term to "a", the AND query would return only row 3, while the OR query would return all 3 rows.

The difference between AND and OR is that AND requires all the items that are "ANDed" together to be true, OR only requires that 1 of them be true.

Upvotes: 2

Dev Sahoo
Dev Sahoo

Reputation: 12101

You can use the AND or OR operators

SELECT * 
FROM question 
WHERE content LIKE '%$search_each%'
AND title LIKE '%$search_each%'
AND summary LIKE '%$search_each%'

Upvotes: 1

Related Questions