I have a table of products, a table of custom definitions, and a table of values:
products
id product_name price
48 product one 32.99
87 another product 2.50
...etc
fielddefs
id name
6 brand
9 colour
23 flavour
...etc
fieldvals
product_id fielddef_id value
48 6 Rowntree
48 9 Red
48 23 Strawberry
87 6 Cadburys
87 9 Yellow
87 23 Lemon
etc...
I am now trying to do a search using a filter with drop-down selections for each fielddef:
$sql = "SELECT * FROM products INNER JOIN fieldvals ON fieldvals.product_id=products.id WHERE product_name LIKE '%".$q."%' AND (fielddef_id='7' AND value='".$c."') AND (fielddef_id='8' AND value='".$b."') AND (fielddef_id='9' AND value='".$f."') AND (fielddef_id='10' AND value='".$t."') AND (fielddef_id='5' AND value='".$h."') AND (fielddef_id='6' AND value='".$v."')";
An echo of the SQL gives me something like:
SELECT * FROM products INNER JOIN fieldvals ON fieldvals.product_id=products.id WHERE product_name LIKE '%cola%' AND (fielddef_id='7' AND value='Purple') AND (fielddef_id='9' AND value='Apple') AND (fielddef_id='10' AND value='Party') AND (fielddef_id='5' AND value='true') AND (fielddef_id='6' AND value='true')
This code only works for one criteria after the $q - ie you can include $q and $c, or $q and $h, or $q and $v, and it successfully finds matching products, but multiple nested AND statements do not seem to work.
Where am I going wrong?
This link offers a similar question where someone wanted to query from the same "field data" table and wanting multiple conditions.
The issue you are encountering is that for any single record, none of them can have MULTIPLE values for a given column, only a result of comparing multiple records and applying a HAVING COUNT(*) = criteria you are looking for. The other (per my link above) shows that. Now how can this similar approach be applied to your problem.
SELECT
P.ID,
P.Product_Name,
P.Price
FROM
products P
INNER JOIN fieldvals FV1
ON P.id = FV1.product_id
AND FV1.FieldDef_ID = '7'
AND FV1.Value = 'value expected for 7'
INNER JOIN fieldvals FV2
ON P.id = FV2.product_id
AND FV2.FieldDef_ID = '8'
AND FV2.Value = 'value expected for 8'
INNER JOIN fieldvals FV3
ON P.id = FV3.product_id
AND FV3.FieldDef_ID = '9'
AND FV3.Value = 'value expected for 9'
(continue same "join" sample above for as many
criteria conditions you need to add... just keep
incrementing the alias ... FV1, FV2, FV3, etc...)
WHERE
P.Product_Name like '%your criteria%'
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.