I have a table that contain products with their specifications.i created a sample of data in http://sqlfiddle.com/#!2/15575/1 .I want create search form that users can search products by their specifications.for example user search laptop with RAM=2 and VGA=512 or VGA=1. I wrote a query,but not working.please help me. this example: result: 1525,1535,k5,k6
select product
from my_table
where (custom = 'Ram' and custom_value = '2')
or (custom = 'vga' and custom_value in ('1', '512'))
group by product
having count(distinct custom) = 2
Example:
I'm interpreting your request as: - Within each of your criteria, you want an OR
clause. - all the criteria are AND
ed together.
So, for your sample above, you would want:
SELECT products.product FROM
(select distinct product from my_table) as products
where
exists (
select * from my_table where products.product = my_table.product
and custom='Ram' and custom_value='2')
and exists (
select * from my_table where products.product = my_table.product
and custom='vga' and custom_value in('512','1'))
Where you start with the unique list of products, and then check each criteria to see if a value exists for that product.
SQL Fiddle here: http://sqlfiddle.com/#!2/15575/35
Having said that, you should redesign your tables.
You can see from this query what a starting point to a redesign might be. First, create a table that just lists the unique products. Then create tables for each of the criteria. Or expand the table of the unique products to have each of those custom values ('Ram', 'vga', etc.) as columns in the table of unique products.
You want an or
where you have an and
I think:
SELECT product, count(*) as prod_count FROM my_table
WHERE (custom='Ram' and custom_value='2')
or (custom='vga' and custom_value in('512','1'))
group by product
having prod_count = 2
First of all, I'd recommand you use a different DB structure:
CREATE TABLE COMPANY (ID INT, NAME VARCHAR(50), PRIMARY KEY(ID));
CREATE TABLE RAM (ID INT, NAME VARCHAR(50), PRIMARY KEY(ID));
CREATE TABLE CPU (ID INT, NAME VARCHAR(50), PRIMARY KEY(ID));
CREATE TABLE VGA (ID INT, NAME VARCHAR(50), PRIMARY KEY(ID));
Then use a relational table to specify products properties:
CREATE TABLE PRODUCT_PROPERTIES (
ID_PRODUCT INT REFERENCES PRODUCT(ID),
ID_COMPANY INT REFERENCES COMPANY (ID),
ID_RAM INT REFERENCES RAM (ID),
ID_CPU INT REFERENCES CPU (ID),
ID_VGA INT REFERENCES VGA (ID),
PRIMARY KEY(ID_PRODUCT)
);
Then using simple JOINS and a simple SELECT on your PRODUCT_PROPERTIES
you can filter your results easily.
Hope this helps..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.