2014-02-20 31 views
1

记录我有一个表,看起来像这样 表 - MYLIST选择加起来数量

----- 
id | max_p 
---------- 
1 | 4 
2 | 2 
3 | 2 
4 | 6 
5 | 2  
6 | 2 

我想运行一个查询,将发现的最小行数,其中总和max_p = 10。所以在这种情况下,将选择记录1和4

,如果我想运行相同的查询找到12话,那就选择记录1,4和5

,如果我想找到这等于2-5它记录将只选择第5条记录,因为这是正确的数字,因此不需要选择多于一条记录?

理想,这将只选择一个记录,如果所需的量是一样的任一行,然后如果这是不可能的,将选择两个记录,然后是三个等。如果需要的数量是不可能的,那么它将返回一个空结果

小提琴这里:http://ideone.com/3ECaT2

CREATE TABLE `my_list` (
    `id` int(2) , 
    `max_p` int(2), 
    PRIMARY KEY (`id`) 
) ; 


INSERT INTO `my_list` (`id`, `max_p`) VALUES 
(1, 4), 
(2, 2), 
(3, 2), 
(4, 6), 
(5, 2), 
(6, 2); 

任何帮助,不胜感激

+4

检索整个数据集,并做到这一点的客户端。 .. –

回答

2

在SQL真正解决这个问题,就需要递归子查询。 MySQL不提供此功能。你可以做的就是寻找这样的组合,最多可以有一定数量的元素。下面的查询实现了这四个组合:

select ml1.max_p as p1, ml2.max_p as p2, ml3.max_p as p3, ml4.max_p as p4 
from my_list ml1 left outer join 
    my_list ml2 
    on ml1.id < ml2.id left outer join 
    my_list ml3 
    on ml2.id < ml3.id left outer join 
    my_list ml4 
    on ml3.id < ml4.id 
where coalesce(ml1.max_p, 0) + coalesce(ml2.max_p, 0) + coalesce(ml3.max_p, 0) + coalesce(ml4.max_p, 0) 

为了获得最短的,算元素的数量和使用limit

select ml1.max_p as p1, ml2.max_p as p2, ml3.max_p as p3, ml4.max_p as p4 
from my_list ml1 left outer join 
    my_list ml2 
    on ml1.id < ml2.id left outer join 
    my_list ml3 
    on ml2.id < ml3.id left outer join 
    my_list ml4 
    on ml3.id < ml4.id 
where coalesce(ml1.max_p, 0) + coalesce(ml2.max_p, 0) + coalesce(ml3.max_p, 0) + coalesce(ml4.max_p, 0) 
order by ((ml1.map_p is null) + 
      (ml2.map_p is null) + 
      (ml3.map_p is null) + 
      (ml4.map_p is null) 
     ) desc 
limit 1; 
+1

+1挺整齐。除当然:) – Bohemian

+0

谢谢您的回答戈登的格式。当我尝试运行任何查询我得到一个错误说“不是唯一的表/别名:‘ML2’” 道歉是这样一个新手 – user3332419