根据排序值创建新项目

时间:2010-10-07 22:19:32

标签: mysql

我遇到的情况是我正在根据另一列的排序值构建一个新列表。

例如 表:产品 id,name,sort_order,expiration_date

表:列表 id,product_id

假设我想在列表中按顺序总共有15个产品。但是,产品过期,当发生这种情况时,它们将从列表中删除,然后我们需要根据sort_order(列表中的最后一个sort_order id,如果它存在)添加基于“next in line”的新产品如果没有,重新开始。)

我希望这是有道理的......

但我的问题是,有没有办法在一个查询中处理这一切?

现在,我就是这样做的:

    Query 1: SELECT count(*), sort_order as so FROM lists ORDER BY sort_order DESC

if($count < 15){
    $difference = 15 - $count;
    for($c = $count; $c >= 1; $c -=1){
        Query 2: SELECT id FROM products WHERE sort_order = $so + 1 LIMIT 1
        if(results = 0){
             Query 3: SELECT id FROM products ORDER BY sort_order ASC LIMIT 1

             Query 4: INSERT (id) into lists

        }else{

             Query 5: INSERT (id) INTO LISTS

        }
    }
}

对于一个相当简单的任务看似很多查询......任何建议都会很大!

谢谢!

2 个答案:

答案 0 :(得分:0)

嗯,这样的事情(我对这个过程并不完全清楚,但你明白了。)

  $start_sort_order = N;//whatever integer it is.


  INSERT INTO lists (id)
  SELECT id FROM products 
  ORDER BY 
     sort_order < $start_sort_order, -- sort_order > $start_order == 0 => earlier, 
                                     -- sort_order < $start_order == 1 => at the end
     sort_order                      -- afterwards standard (so a result could be 
                                     -- like : 89,90,93,96,97,99,4,5,6,7, etc...
  LIMIT 15;

答案 1 :(得分:0)

获取max_sort_order和current_sort_order

select id, if (p.sort_order > current_sort_order,
     sort_order - $current_sort_order + $max_sort_order,  
     sort_order - $current_sort_order) 'relative_sort_order' from product 

order by relative_sort_order asc 
limit 15;
相关问题