8
8
891099838382018-06-22 15:02:16
MySQL
89109983838, 2018-06-22 15:02:16

How to create a Mysql query with a filter on one column of several values?

There is a simple code with a request (let's find out if there is a filter by parameters - categories, brand, filter):

SELECT COUNT(*) AS total FROM product_filter f
LEFT JOIN product p ON(f.product_id = p.product_id)
LEFT JOIN product_to_category c ON(p.product_id = c.product_id)
WHERE f.filter_id = '" . (int)$filter_id . "' AND c.category_id = '".(int)$category_id."' AND p.manufacturer_id = '".(int)$manufacturer_id."'"

It works all right!
BUT I can’t form a request in any way to also get $filter_id BY SEVERAL VALUES, that is, I need to get the number of product records that have several filters marked.
I tried f.filter_id IN (1,3,7) not that, because it returns any of the options, but it is necessary if there are a bunch of filters for one product. I experimented with UNION - without result, but something, I had not met him before.
P.S.: there are only two columns product_id and filter_id in the product_filter table, that is, one product can have several filter ids by its id.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
8
89109983838, 2018-06-24
@89109983838

Thanks to SharuPoNemnogu - your comment is somehow not marked as a decision ... I paint the finished version here.
IT HAPPENED SO!:
Considering that we initially do not know how many filters there will be in the request:

// $category_id = id  категории;
// $manufacturer_id = id производителя

$value = implode(',', $val_str);   //(массив id фильтров приводим к 'x,a,b,z.......' 
$value_num = count($val_str);  // считаем сколько фильтров -  чтоб в группе sql указать

!(structure DB CMS OPENCART)!
$query = "SELECT COUNT(DISTINCT p.product_id) AS total FROM product p
LEFT JOIN product_filter f ON(p.product_id = f.product_id)
LEFT JOIN product_to_category c ON(p.product_id = c.product_id)
WHERE f.filter_id in (". $value .") AND c.category_id = '".(int)$category_id."' AND p.manufacturer_id = '".(int)$manufacturer_id."'
GROUP BY p.product_id having count(f.filter_id) = '".$value_num."'";

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question