Forum Moderators: coopster

Message Too Old, No Replies

Simplifying a basic mySQL query

Gotta be a better way

         

mipapage

9:36 am on Oct 27, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hey all, here I will reveal in dramatic fashion my weak mySQl skills ;-]

I have a query of the following format. I'm using * for simplicity here, I'm only selecting 5 fields...


SELECT * FROM mytable WHERE
field1 = 'x' and field2 = 'y' and field3 = 'a'
OR
field1 = 'x' and field2 = 'y' and field3 = 'b'
OR
field1 = 'x' and field2 = 'y' and field3 = 'c'

Should there not be some way that I can write this in a - for lack of a better description - more 'compunded' format?

Do I have to write the "field1 = 'x' and field2 = 'y'" part each and every time? In some instances there can be up to 50 different values for field3, and the query gets a bit wordy...

The query itself is automatically generated, so perhaps this isn't so important, or is it? Does the size of the query matter, or is it okay as long as it gets the job done ;-]?

mincklerstraat

10:14 am on Oct 27, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm no mysql genious myself, but you could try (I think this should work):

$query = "SELECT * FROM mytable WHERE
(field1 = 'x' and field2 = 'y') and (field3 = 'a' or field3 = 'b' or field3 = 'c')";

mipapage

10:30 am on Oct 27, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I knew it was something like that. Thanks it works fine!

coopster

12:53 pm on Oct 27, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You could also build a string of values and use the IN [dev.mysql.com] operator...
$values = "'a','b','c'"; 
$query = "SELECT * FROM mytable WHERE
field1 = 'x' and field2 = 'y' AND field3 IN($values)";
This works well when you want to build that list dynamically.

mipapage

1:40 pm on Oct 27, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ahh, thanks coopster.

I am building it dynamically, but in a way that the first method works out okay.

I'm trying your out anyway.

BTW, I RTFM, but the mysql manual leaves something to be desired... ;-]