我有很多关系的表:
参数
+-------------------+-----------------------+
| 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中执行此操作?
答案 0 :(得分: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
答案 1 :(得分: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;