【问题标题】:How to filter database table by a multiple join records from another one table but different types?如何通过来自另一个表但不同类型的多个连接记录来过滤数据库表?
【发布时间】:2019-11-18 03:06:05
【问题描述】:

我有一个products 表和对应的ratings 表,其中包含一个外键product_idgrade(int)type,这是一个接受值robustnessprice_quality_ratio 的枚举

等级接受从 1 到 10 的值。例如,如果我想过滤 robustness 的最低等级为 7 且price_quality_ratio 的最低等级为 8 的产品,查询会是什么样子?

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    您可以加入两次,每次评分一次。 inner joins 消除了不符合任何评级标准的产品,

    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
    

    另一种选择是使用做条件聚合。这只需要一个join,然后是一个group by;在having 子句中检查评级标准。

    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
    

    【讨论】:

      【解决方案2】:

      @GMB 提出的JOIN 也是我的第一个建议。如果由于必须维护太多 rX.ratings 而变得过于复杂,您还可以使用嵌套查询:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-12
        • 1970-01-01
        • 1970-01-01
        • 2014-10-05
        • 2013-11-11
        • 1970-01-01
        相关资源
        最近更新 更多