Combining ANDs and ORs within MYSQL query

MadJuggla9

2[H]4U
Joined
Oct 9, 2002
Messages
3,515
With search engine AI .... it misinterprets what I'm searching for .... I need it to be dumb for my search. I'm weeding out some unwanted data and the simplest way to do it would be to use multiple ANDs and ORs. It will only be used for one small script so I didn't frantically search google for more sophisticated ways.

For the sake of the argument, lets say I wanted to select from a table of people that used dialup internet or high speed internet and I only wanted dialup users with names like Jones, Thomas, and Smith.

Something very simple that doesnt work could be constructed like so:
Code:
SELECT first_name, last_name, connection_type
FROM mytable
WHERE connection_type = 'dialup' AND last_name='Jones' OR last_name='Smith' OR last_name='Thomas';

It will obviously break on the first OR statement. What are some ways around this? I didn't want to look too far in the wrong direction. Should I be looking to include an IN clause in my query? A more practical way? possible with ANDs and ORs by grouping with () or '' or anything?
 
Doesn't this work?

Code:
SELECT first_name, last_name, connection_type
FROM mytable
WHERE connection_type = 'dialup' AND (last_name='Jones' OR last_name='Smith' OR last_name='Thomas');

For some reason I can't remember if you can use ()'s in mysql.

I think I may be treating your question wrong, but the way I've interpretted it, you want connection_type='dialup' AND (Last name to be one of those 3 things)

EDIT:

You could also probably do this:

Code:
SELECT first_name, last_name, connection_type
FROM my_table
WHERE connection_type='dialup' AND last_name IN ('Jones', 'Smith', 'Thomas')
 
Doesn't this work?

Code:
SELECT first_name, last_name, connection_type
FROM mytable
WHERE connection_type = 'dialup' AND (last_name='Jones' OR last_name='Smith' OR last_name='Thomas');

For some reason I can't remember if you can use ()'s in mysql.

I think I may be treating your question wrong, but the way I've interpretted it, you want connection_type='dialup' AND (Last name to be one of those 3 things)

EDIT:

You could also probably do this:

Code:
SELECT first_name, last_name, connection_type
FROM my_table
WHERE connection_type='dialup' AND last_name IN ('Jones', 'Smith', 'Thomas')

I forgot about parenthesis working, by the time I found some old code, you had replied correctly. Thanks!

Cleared it up 100%, I will be looking into the 'IN' clause for larger purposes. God I feel stupid.


Here's what it fixed, I needed wildcards so I avoided the IN clause:
Code:
$query = "SELECT * FROM surveys WHERE town='$value' " . 
	"AND (install_time LIKE '%$this_mon%' OR install_time LIKE '%$last_mon%' OR install_time LIKE '%$next_mon%')";
 
Back
Top