[英]How to count and sort data in junction table
I have tables with many to many relationship: 我的表之间存在多对多关系:
Parameters 参量
+-------------------+-----------------------+
| Field | Type |
+-------------------+-----------------------+
| id | int(11) |
| name | varchar(20) |
Product 产品
+-------------------+-----------------------+
| Field | Type |
+-------------------+-----------------------+
| id | int(11) |
| name | varchar(20) |
Parameters_Product 参数_产品
+-------------------+-----------------------+
| Field | Type |
+-------------------+-----------------------+
| id_parameters | int(11)FK |
| id_product | int(11)FK |
So, product may have some parameters, parameters may relates to products. 因此,产品可能具有一些参数,参数可能与产品有关。 When I choose several parameters I need to output the sorted names of products which contains checked parameters, but sorting must be based on the number of match parameters, but more than one. 当我选择多个参数时,我需要输出包含已检查参数的产品的排序名称,但是排序必须基于匹配参数的数量,但不能超过一个。
Example: 例:
Parameters_Product 参数_产品
+---------+----------+
|id_param |id_product|
+--------------------+
| 1 | 1 |
| 2 | 1 | ----> Product#1
| 3 | 1 |
| 4 | 1 |
----------------------
| 1 | 2 |
| 2 | 2 |
| 6 | 2 | ----> Product#2
| 4 | 2 |
| 9 | 2 |
----------------------
| 5 | 3 |
| 7 | 3 | ----> Product#3
| 1 | 3 |
Client chooses Id_params: 1,2,6,9. 客户选择Id_params:1、2、6、9。
Result in order: 结果如下:
Product#2 -> 4 matches
Product#1 -> 2 matches
Product#3 -> 1 matches (doesn't outputted)
I did it in php with terrible code, but I think it can be resolved easier. 我在php中使用了糟糕的代码,但是我认为它可以更轻松地解决。
How to do this in SQL? 如何在SQL中执行此操作?
you have to group by id_product field, filter single results with id_param values and then order by the id_param count. 您必须按id_product字段分组,使用id_param值过滤单个结果,然后按id_param计数排序。 like this: 像这样:
SELECT name
FROM Parameters_Product
INNER JOIN Parameters ON id_product = id
WHERE id_param IN (1,2,6,9)
GROUP BY id_product
HAVING COUNT(id_param) > 1
ORDER BY COUNT(id_param) desc
If you need just id_product: 如果只需要id_product:
select id_product,
count(id_param) as matches
from Parameters_Product
where
id_param in (1,2,6,9)
group by id_product
having count(id_param) >1
order by matches desc;
If you need Product Name: 如果您需要产品名称:
select p.name,count(pp.id_param) as matches
from
Product p
join Parameters_Product pp
on p.id=pp.id_product
where
pp.id_param in (1,2,6,9)
group by p.name
having count(pp.id_param) >1
order by matches desc;
OR 要么
select p.name,pp.matches from Product p
join
(select id_product,
count(id_param) as matches
from Parameters_Product
where
id_param in (1,2,6,9)
group by id_product
having count(id_param) >1) pp
on p.id = pp.id_product
order by pp.matches desc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.