This type of design is called an EAV design and there are a lot of potential problems for the unwary - not least when you data set grows beyond a certain size. I'll assume you have table structure like:
Code:
create PARAMS table (
ID
FIELD
VALUE
)
First make sure you have indexes like:
Code:
create index idx1 on PARAMS ( VALUE, FIELD, ID )
and
create index idx2 on PARAMS ( ID, FIELD, VALUE )
Then the SQL to do your (A AND B AND C) example would be:
Code:
select ID
from PARAMS p1
where VALUE = 'z'
and FIELD = 'f3'
and exists(
select 1
from PARAMS p2
where p2.ID = p1.ID
VALUE = 'y'
and FIELD = 'f2' )
and exists(
select 1
from PARAMS p2
where p2.ID = p1.ID
VALUE = 'x'
and FIELD = 'f1' )
You also give some code to do this as ( Select item_id where (Field = 'f1' AND VALUE = 'x') AND (FIELD = 'f2' AND VALUE= 'y') OR (FIELD ='f3' AND VALUE='z') but this obviously won't work as you to join to the table multiple times for multiple fields.
For your (A OR B) AND C query I'd use would be (C here is f3=z):
Code:
select ID
from PARAMS p1
where VALUE = 'z'
and FIELD = 'f3'
and (
exists(
select 1
from PARAMS p2
where p2.ID = p1.ID
VALUE = 'y'
and FIELD = 'f2' )
or exists(
select 1
from PARAMS p2
where p2.ID = p1.ID
VALUE = 'x'
and FIELD = 'f1' ) )
The important thing is to make sure the initial part of the query narrows down the search ie you don't want where FIELD='GENDER' and VALUE='MALE' but FIELD='NAME' and VALUE='Bealzebub'.
Can you try the above queries with some typical data and post some response times - if you're still having issues then could you detail the indexes you have the table definition and then supply a typical query that is running slow.
I'd also look at writing a function that can return the VALUE for and FIELD for a given ID - this will make your code much easier to read ie
select my_get_param_func( ID, FIELD )
Mike