[英]How to filter database table by a multiple join records from another one table but different types?
I have a products
table and corresponding ratings
table which contains a foreign key product_id
, grade(int)
and type
which is an enum accepting values robustness
and price_quality_ratio
我有一个products
表和相应的ratings
表,其中包含一个外键product_id
, grade(int)
和type
,它是一个接受值的枚举, robustness
和price_quality_ratio
The grades accept values from 1 to 10. So for example, how would the query look like, if I wanted to filter the products where minimum grade for robustness
would be 7 and minimum grade for price_quality_ratio
would be 8?等级接受从 1 到 10 的值。例如,如果我想过滤robustness
最低等级为 7 且price_quality_ratio
最低等级为 8 的产品,查询会是什么样子?
You can join twice, once per rating.您可以加入两次,每次评分一次。 The inner join
s eliminate the products that fail any rating criteria, inner join
消除了不符合任何评级标准的产品,
select p.*
from products p
inner join rating r1
on r1.product_id = p.product_id
and r1.type = 'robustness'
and r1.rating >= 7
inner join rating r2
on r2.product_id = p.product_id
and r2.type = 'price_quality_ratio'
and r2.rating >= 8
Another option is to use do conditional aggregation.另一种选择是使用做条件聚合。 This requires only one join
, then a group by
;这只需要一个join
,然后一个group by
; the rating criteria are checked in the having
clause. having
have子句中检查评级标准。
select p.product_id, p.product_name
from products p
inner join rating r
on r.product_id = p.product_id
and r.type in ('robustness', 'price_quality_ratio')
group by p.product_id, p.product_name
having
min(case when r.type = 'robustness' then r.rating end) >= 7
and min(case when r.type = 'price_quality_ratio then r.rating end) >= 8
The JOIN
proposed by @GMB would've been my first suggestion as well. @GMB 提出的JOIN
也是我的第一个建议。 If that gets too complicated with having to maintain too many rX.rating
s, you can also use a nested query:如果由于必须维护太多rX.rating
而变得过于复杂,您还可以使用嵌套查询:
SELECT *
FROM (
SELECT p.*, r1.rating as robustness, r2.rating as price_quality_ratio
FROM products p
JOIN rating r1 ON (r1.product_id = p.product_id AND r1.type = 'robustness')
JOIN rating r2 ON (r2.product_id = p.product_id AND r2.type = 'price_quality_ratio')
) AS tmp
WHERE robustness >= 7
AND price_quality_ratio >= 8
-- ORDER BY (price_quality_ratio DESC, robustness DESC) -- etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.