Mysql查询具有多个ORDER BY子句和IF条件

时间:2017-02-21 05:37:37

标签: mysql

我正在尝试根据订单表中的这些条件进行查询,

var countMap = {};
  var counter = 0;
  $('#share_table_body').find('.js-post').each(function () {
    var totalCount = 0;
    $(this).find('.js-social').each(function () {
      var $this = $(this);
      var socialType = $(this).data('social-type');
      var url = $this.closest('.js-post').data('url');
      getShareStatus(url, socialType)
        .then(function (shareCount) {
          $this.text(shareCount);

          if (!countMap[socialType]) {
            countMap[socialType] = 0;
          }
          if (!countMap['total']) {
            countMap['total'] = 0;
          }

          countMap[socialType] += shareCount;

          totalCount += shareCount;

          countMap['total'] += shareCount;

          $this.siblings('.js-total').text(totalCount);
        })
        .fail(function (err) {
          $('.error-notice').removeClass('hidden');
          $this.css('color', 'red').text('!');
        });
    });
    counter++;
  });
  if (counter == $('#share_table_body').find('.js-post').length) {
    console.log(countMap);
    $('.total-facebook').text(countMap['facebook']);
  }

这就是我所拥有的,

// This is not an actual query
SELECT *
IF (store_id = 3) THEN ORDER BY WEIGHT DESC, 
ELSEIF (STORE_ID = 7) THEN ORDER BY WEIGHT DESC
ELSEIF ORDER BY WEIGHT = DESC  
ELSEIF (EQUAL WEIGHT) ORDER BY ORDER_DATE DESC
ELSEIF (EQUAL WEIGHT AND EQUAL ORDER_DATE) ORDER BY STORE_ID DESC
ELSEIF (EQUAL WEIGHT AND EQUAL ORDER_DATE AND EQUAL STORE_ID) ORDER BY 
SHIPPING_METHOD DESC 
FROM TABLE orders WHERE carrier_name = 'XXX'

获得的结果是

enter image description here

我不确定为什么53.39和30.35没有排序。我究竟做错了什么? 请建议是否有更好的方法来实现这一点。

这是必需的结果,

enter image description here

2 个答案:

答案 0 :(得分:1)

根据您的预期输出,以下查询应该为您提供所需内容:

SELECT *
FROM orders
WHERE carrier_name = 'XXX'
ORDER BY CASE WHEN store_id = 3 THEN 0
              WHEN store_id = 7 THEN 1
              ELSE 2 END,
         store_id,
         weight DESC

有关ORDER BY子句中逻辑的解释,第一个条件首先放置store_id 3,然后放7,接着是其他所有内容。下一个条件按store_id按升序对这三个组中的每个组进行排序。请注意,对于3和7,将忽略此第二步,因为store_id值对于这些组(分别为3和7)是相同的。最后,第三个条件是按重量按降序排序。

答案 1 :(得分:0)

ORDER BY 
  weight DESC, -- as i can see all true in your cases
  order_date DESC,
  store_id DESC,
  shipping_method DESC