MySQL多重搜索条件不返回任何结果,但如果删除最后一行则有效

时间:2011-09-14 14:42:40

标签: mysql search

我在Mysql DB上有这个查询: -

SELECT DISTINCT model.model_id, model.model_ref, 
model.manufact_year, model.discontinued_year, model.mini_spec, 
model.equiv_model_id
FROM model 
LEFT JOIN model_custom_field 
ON model_custom_field.model_id = model.model_id
WHERE model.category_id = 140 AND model.manufacturer_id = 1190
AND (model_custom_field.custom_detail_id = 1070 AND model_custom_field.custom_detail_val = '15.6')
AND (model_custom_field.custom_detail_id = 1010 AND model_custom_field.custom_detail_val = 'Dedicated') 

虽然搜索有效数据,但返回的结果为零。

如果我删除它的最后一行。

我最后两行的括号是因为custom_detail_id和custom_detail_val是链接的。

有人可以告诉我是否有统计数据的格式 这是正确的。


我知道最后两个陈述是矛盾的,不可能有效,但我需要知道是否有一种方法可以将最后两个结合在一个联合中。

2 个答案:

答案 0 :(得分:2)

据我所知,您的model_custom_field表包含model的各种扩展属性的列表,这些属性是使用EAV model实现的(无双关语)。并且您希望找到具有两个具有特定值的特定属性的模型。

假设单个model_id无法在custom_detail_id中重复custom_detail_valmodel_custom_field的组合:

SELECT
  m.model_id,
  m.model_ref,
  m.manufact_year,
  m.discontinued_year,
  m.mini_spec,
  m.equiv_model_id
FROM model m
  INNER JOIN (
    SELECT model_id
    FROM model_custom_field
    WHERE (custom_detail_id = 1070 AND custom_detail_val = '15.6')
       OR (custom_detail_id = 1010 AND custom_detail_val = 'Dedicated')
    GROUP BY model_id
    HAVING COUNT(*) = 2
  ) f ON m.model_id = f.model_id
WHERE m.category_id = 140 
  AND m.manufacturer_id = 1190

替代解决方案:

SELECT
  m.model_id,
  m.model_ref,
  m.manufact_year,
  m.discontinued_year,
  m.mini_spec,
  m.equiv_model_id
FROM model m
  INNER JOIN model_custom_field f1070 ON m.model_id = f1070.model_id
  INNER JOIN model_custom_field f1010 ON m.model_id = f1010.model_id
WHERE m.category_id = 140 
  AND m.manufacturer_id = 1190
  AND (f1070.custom_detail_id = 1070 AND f1070.custom_detail_val = '15.6')
  AND (f1010.custom_detail_id = 1010 AND f1010.custom_detail_val = 'Dedicated')

答案 1 :(得分:0)

如果我理解你要做的事情,那么试试这个:

SELECT DISTINCT model.model_id, model.model_ref,  model.manufact_year, model.discontinued_year, model.mini_spec,  model.equiv_model_id 
FROM model  
LEFT JOIN model_custom_field  ON model_custom_field.model_id = model.model_id 
WHERE model.category_id = 140 
AND model.manufacturer_id = 1190 
AND ((model_custom_field.custom_detail_id = 1070 AND model_custom_field.custom_detail_val = '15.6') 
or (model_custom_field.custom_detail_id = 1010 AND model_custom_field.custom_detail_val = 'Dedicated'))