如何以最低成本获得最大前缀记录?

时间:2016-03-15 09:52:44

标签: mysql sql

我有一张表价格

共有4个字段,如

+----+--------------+----------+------------+  
| Id | Prefix       |  rate    |  Ref_id  
+----+--------------+----------+------------+    
| 1  |     51       |    0.30  |    2      
| 2  |     51888    |    0.20  |    2    
| 3  |     51       |    0.10  |    1    
| 4  |     5188     |    0.10  |    1    
| 5  |     518      |    0.10  |    1

现在我想获得每个Ref_id具有最大长度前缀值的记录。

因此,在Ref_id 2中,前缀总数为2,但前缀值最长为

+----+--------------+----------+------------+
| Id | Prefix       |  rate    |  Ref_id  
+----+--------------+----------+------------+  
| 2  |   51888      | 0.20     | 2  

和Ref_id 1总共有3个前缀,且前缀最长为

+----+--------------+----------+------------+
| Id | Prefix       |  rate    |  Ref_id
+----+--------------+----------+------------+
| 4  |     5188     |    0.10  |    1

在这两个值之后,它必须在内部短路并返回最终输出,如

+----+--------------+----------+------------+
| Id | Prefix       |  rate    |  Ref_id
+----+--------------+----------+------------+
| 4  |     5188     |    0.10  |    1
| 2  |     51888    |    0.20  |    2

因为它会以最低的成本获得每个Ref_id最长的前缀。

我确实尝试过但只能获得最长的前缀,但却无法获得最长的前缀,然后以最低的速率对该值进行排序。

2 个答案:

答案 0 :(得分:0)

我做了一些假设 - 但你明白了......

SELECT x.* 
  FROM price x
  JOIN
     ( SELECT ref_id, MAX(LENGTH(prefix)) longest FROM price GROUP BY ref_id ) y
    ON y.ref_id = x.ref_id 
   AND y.longest = LENGTH(x.prefix)
 ORDER BY id DESC;

答案 1 :(得分:0)

您可以使用group by with inner query,例如:

    select ref_id as id, 
    (select prefix from price where ref_id = id order by length(prefix) desc limit 1) as prefix,
(select min(rate) from price where ref_id = id) as rate
        from price
        group by ref_id
        order by prefix