Grouping WHERE with ()

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
LiveFree
Forum Contributor
Posts: 258
Joined: Tue Dec 06, 2005 5:34 pm
Location: W-Town

Grouping WHERE with ()

Post by LiveFree »

Good Morning to you!

I have a search query where a number of preset conditiosn need to be true, but there is an OR in there and that messes the whole query up because if the OR is true then the query returns a result.

So what Im asking is there a way to group WHERE clauses in () to have only that portion evalute seperatly from the rest?

SELECT .... FROM ... WHERE genre='Rock' AND (format='MP3' OR format='AIFF')

Thanks!
User avatar
SimonJ621
Forum Commoner
Posts: 36
Joined: Thu Jul 27, 2006 5:07 am
Location: Ohio

Post by SimonJ621 »

You should be able to use a sub-query, in other words...


SELECT ....
FROM ...
WHERE genre='Rock' AND (
SELCET ...
FROM ...
WHERE format='MP3' OR format='AIFF');


Something like that at least. I'm not sure if that's exactly what you're looking for but just remember, sql runs the sub-query first. Hope it helps.

Jason
User avatar
SimonJ621
Forum Commoner
Posts: 36
Joined: Thu Jul 27, 2006 5:07 am
Location: Ohio

Post by SimonJ621 »

Hmm... now that I think about it, I think you can just do what you were originally asking...

SQL allows compound queries to be made using ( ), allthough it might make more sense to do the (X or X) first:

SELECT .... FROM ... WHERE format='MP3' OR format='AIFF') AND genre='Rock'

Ok, hope that helps more,

Jason
LiveFree
Forum Contributor
Posts: 258
Joined: Tue Dec 06, 2005 5:34 pm
Location: W-Town

Post by LiveFree »

Anybody know from what vers. of MySQL up that works with?

Edit: MysQL 4.1

Thanks pal
Last edited by LiveFree on Thu Jul 27, 2006 9:53 am, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

not all servers support subqueries Simon.

LiveFree, I'm not too sure what you're asking. Your query, as-is, looks fine from here.
User avatar
SimonJ621
Forum Commoner
Posts: 36
Joined: Thu Jul 27, 2006 5:07 am
Location: Ohio

Post by SimonJ621 »

feyd wrote:not all servers support subqueries Simon.

LiveFree, I'm not too sure what you're asking. Your query, as-is, looks fine from here.
True, but it's been supported for a couple of years now. I think it's safe to assume that most servers are using at least 4.1. Regardless, they aren't needed here. You are right in saying his query looks fine the way it is. I originally read it and thought LiveFree wanted something else.

Jason
Post Reply