【问题标题】:Is there a way to make a query follow a hierarchy in SQL?有没有办法让查询遵循 SQL 中的层次结构?
【发布时间】:2016-05-31 12:24:10
【问题描述】:

我有一组数据,其中有很多卖家,但我们有一个我们喜欢的卖家层次结构,并希望为每种产品选择最畅销的卖家。

ID |ITEM   | price   | Seller
===========================
1  |Laptop | 100     | eBay
2  |Laptop | 125     | Amazon
3  |Apple  | 5       | Amazon

因此,当我查询笔记本电脑的这些数据时,我希望每件商品都拥有最畅销的卖家。我对卖家的层次结构是 1. ebay 2. Amazon 所以本质上它只会返回第一条和第三条记录。

你会怎么做呢?

【问题讨论】:

    标签: mysql sql oracle sqlite amazon-web-services


    【解决方案1】:

    您可以通过子查询获得:

    SELECT *
    FROM tbl t1
    WHERE (t1.id, t1.item, t1.price) IN
        (SELECT t2.id, t2.item, t2.price
         FROM tbl t2
         WHERE t1.id = t2.id
         ORDER BY t2.price
         LIMIT 1);
    

    【讨论】:

      【解决方案2】:

      在 Oracle、MySQL 和 SQLite 中测试的查询:

      select s.* from sellers s
        join (select item, min(price) mp from sellers group by item) ms
          on s.item = ms.item and s.price = ms.mp
      

      MySQL Fiddle demo, SQLite Fiddle demo

      对于 Oracle,您可以使用替代查询,它应该更快:

      select id, item, price, seller
        from ( select s.*, min(price) over (partition by item) min_price from sellers s )
        where price = min_price
      

      【讨论】:

        猜你喜欢
        • 2017-03-27
        • 2011-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-07
        • 1970-01-01
        相关资源
        最近更新 更多