1

I have tables like these:

  A table                            B table
--------------------       -----------------------------------
item_ID | item_Name         item_ID | option_ID | option_Value 
--------------------       -----------------------------------
   1      item_a               2         34         2000
   2      item_b               2         45         3400
   3      item_c               2         12         1200  
   4      item_d               3         34         500
   5      item_e               3         13         500
   6      item_f               4         45         700

I wrote a query to get items, for example which have option 34 = 2000 and option 12 = 1200 is:

SELECT A.item_ID, A.item_name
FROM A
LEFT JOIN B ON A.item_ID = B.item_ID
WHERE B.option_ID IN (34, 1200) AND
      B.option_Value IN (1200, 2000) AND
GROUP BY A.item_ID
HAVING COUNT(A.item_ID) >= 2 /* count of option used for search, can be more*/

My problem is for some options I want to get range result , for example: where option id 34 is between 1000 and 2000 and option 12 is lower than 4000

Note : (option_id, option_value) pair is unique and i want to get items that match all of the conditions

4

2 回答 2

2

How about this?

SELECT A.item_ID, A.item_name
FROM A
LEFT JOIN B ON A.item_ID = B.item_ID
WHERE (B.option_ID=34 AND B.option_value BETWEEN 1000 AND 2000)
      OR (B.option_ID=12 AND B.option_value BETWEEN 0 AND 4000)
GROUP BY A.item_ID
HAVING COUNT(A.item_ID) >= 2

Maybe I didn't understand the question completely?

于 2013-03-30T21:41:28.887 回答
2

This should give you what you want:

WHERE
  B.option_ID = 34 AND B.option_Value BETWEEN 1000 AND 2000
  OR
  B.option_ID = 12 AND B.option_Value < 4000

There might be a better way to do this if there was some rule according to which you want to filter... Otherwise, just use OR and AND to achieve what you want.

于 2013-03-30T21:42:07.003 回答