2017-10-19 85 views
-1

我有表有多对多的关系进行排序:如何计算和数据结合表

参数

+-------------------+-----------------------+ 
| Field    | Type     | 
+-------------------+-----------------------+ 
| id    | int(11)    | 
| name    | varchar(20)   | 

产品

+-------------------+-----------------------+ 
| Field    | Type     | 
+-------------------+-----------------------+ 
| id    | int(11)    | 
| name    | varchar(20)   | 

Parameters_Product

+-------------------+-----------------------+ 
| Field    | Type     | 
+-------------------+-----------------------+ 
| id_parameters  | int(11)FK    | 
| id_product  | int(11)FK    | 

所以,产品可能有一些参数,参数可能与产品有关。 当我选择几个参数时,我需要输出包含检查参数的产品的排序名称,但排序必须基于匹配参数的数量,但不止一个。

实施例:

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  | 

客户选择Id_params:1,2,6,9。

结果依次是:

Product#2 -> 4 matches 
Product#1 -> 2 matches 
Product#3 -> 1 matches (doesn't outputted) 

我这么做是可怕的代码PHP,但我认为它可以解决更容易。

如何在SQL中做到这一点?

+3

我们总是乐意帮助和支持新的编码器,但你首先需要帮助自己。 : - )***在[**做更多研究**之后](https://meta.stackoverflow.com/q/261592/1011527)如果你有问题**发布你已经尝试** **清楚说明什么不工作**并提供[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。阅读[如何问](http://stackoverflow.com/help/how-to-ask)一个很好的问题。请务必[参观](http://stackoverflow.com/tour)并阅读[this](https://meta.stackoverflow.com/q/347937/1011527)。 –

+2

您将不得不使用SELECT count()...,JOIN,GROUP BY,ORDER BY的组合。 – Nic3500

回答

1

如果你只需要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; 

如果您需要产品名称:

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; 
1

您必须按id_product字段进行分组,使用id_param值筛选单个结果,然后按id_param计数排序。像这样:

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