Say we have a table that lists all products and the colors in which those products are available:
CREATE TABLE PRODUCT_COLORS( PRODUCT_CODE CHAR(5) NOT NULL, COLOR_CODE CHAR(1) NOT NULL, CONSTRAINT PRODUCT_COLORS_PK PRIMARY KEY (PRODUCT_CODE,COLOR_CODE) );
Data looks like:
Code:
XXXXX R
XXXXX B
YYYYY Y
YYYYY G
ZZZZZ G
ZZZZZ R
Say we want to know which products are available in G(reen) and R(ed), the query is simple, we'll list all products which do have the Red or Green option and then filter out all those that don't have both, getting the desired result (in this case product 'ZZZZZ')
See it in action:
SELECT a.PRODUCT_CODE FROM PRODUCT_COLORS a WHERE a.COLOR_CODE IN ('R', 'G') GROUP BY a.PRODUCT_CODE HAVING COUNT(a.PRODUCT_CODE) = 2
See where I implemented the two conditions? One in the where clause and the second pass to filter out all products which don't have both in the having clause.
Example is built on Firebird, but should work in MySQL, PostgreSQL or any other mainstream database too.
2 comments:
Can also be done using a self JOIN:
mysql> SELECT L.PRODUCT_CODE FROM PRODUCT_COLORS L JOIN PRODUCT_COLORS R ON L.PRODUCT_CODE=R.PRODUCT_CODE WHERE L.COLOR_CODE='R' AND R.COLOR_CODE='G';
+--------------+
| PRODUCT_CODE |
+--------------+
| Z |
+--------------+
1 row in set (0.00 sec)
Shure, but it's more difficult to maintain if you want to let the user choose how many items mean "all"
Post a Comment