duanliaogui4133 2014-10-15 17:54
浏览 103
已采纳

MySQL查询搜索多个属性和value_id

I have a problem with mysql query. for a cuople days I cannot solve it.

URL params ?a=1&b=2&c=3

Structure:

attr_id value_id

query:

SELECT DISTINCT `product_id`
FROM `products_attr_val`
WHERE
    (`attr_id` = '".$searchqueryArray2[0]."' AND `value_id` = '".$searchqueryArray2[1]."')
    OR (`attr_id` = '".$searchqueryArray2[0]."' AND `value_id` = '".$searchqueryArray2[1]."')

but the problem is that if a=12&b=10

and if there is a product with atribute 10 or atribute 12 it shows. I need to show products with a=12 and b=10.

Whats wrong?

Thanks for help.

  • 写回答

1条回答 默认 最新

  • dtrhd2850 2014-10-15 19:26
    关注

    Sounds like you need to use GROUP BY and HAVING clauses.

    SELECT
        `product_id`,
        COUNT (`primary_key_id`) AS `attr_count` /* primary key field here */
    FROM `products_attr_val`
    WHERE
       (`attr_id` = ? AND `value_id` = ?)
       OR (`attr_id` = ? AND `value_id` = ?)
       /* additional as necessary
       OR (`attr_id` = ? AND `value_id` = ?)
       */
    GROUP BY `product_id`
    HAVING `attr_count` = ? /* value here should be equal to number of attributes you are checking for */
    

    Make sure you have a unique index across product_id and attr_id for this to work properly (you should already have this since it would not likely make sense for a product to have multiple records with the same attr_id).

    You also need to make sure you are escaping your values for use in your SQL if you are not already. I am showing these variables here with ? which, if you we using prepared statments, would be a way you might write this SQL.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集