我有一个产品表,一个自定义定义表和一个值表:
产品
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...
我现在尝试使用带有每个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。”')“;
SQL的回声给了我类似的东西:
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 值= '真')
此代码仅适用于$ q之后的一个条件 - 即您可以包含$ q和$ c,或$ q和$ h,或$ q和$ v,并且它成功找到匹配的产品,但是多个嵌套的AND陈述似乎不起作用。
我哪里错了?
答案 0 :(得分:1)
This link offers a similar question有人想从同一个“字段数据”表中查询并想要多个条件。
您遇到的问题是,对于任何单个记录,它们都不能具有给定列的MULTIPLE值,只能比较多个记录并应用您正在寻找的HAVING COUNT(*)=条件。另一个(根据我上面的链接)显示了这一点。现在,如何将这种类似的方法应用于您的问题。
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%'