使用querybuilder根据条件以不同排序顺序对表中的同一列进行排序

时间:2018-08-27 15:06:57

标签: sql doctrine query-builder shopware

我有一个表,在该表上运行条件时,需要根据条件更改条件,在此条件下需要检查条件。 如何使用查询生成器(Doctrine)实现此目的。 例如:表格名称->产品

<table>
  <tr>
    <th>pid</th>
    <th>Lastname</th> 
    <th>instock</th>
    <th>laststock</th> 
    <th>price</th>
  </tr>
  <tr>
    <td>two</td>
    <td>234</td> 
    <td>1</td>
        <td>1</td> 
    <td>101</td>
  </tr>
  <tr>
    <td>three</td>
    <td>345</td> 
    <td>0</td>
        <td>1</td> 
    <td>102</td>
  </tr>
  <tr>
    <td>four</td>
    <td>567</td> 
    <td>2</td>
        <td>1</td> 
    <td>103</td>
  </tr>
  <tr>
    <td>five</td>
    <td>678</td> 
    <td>0</td>
        <td>0</td> 
    <td>104</td>
  </tr>
  <tr>
    <td>one</td>
    <td>123</td> 
    <td>3</td>
        <td>0</td> 
    <td>100</td>
  </tr>
</table>

因此在此表中,我需要首先检查库存值是否大于零,我需要按DESC顺序(库存列)进行订购。否则我需要订购ASC订单(库存列)。如何使用查询生成器执行此操作?

我需要这样的输出

<table style="width: 100%;">
<tbody>
<tr>
<th>pid</th>
<th>Lastname</th>
<th>instock</th>
<th>laststock</th>
<th>price</th>
</tr>
<tr>
<td>one</td>
<td>123</td>
<td>3</td>
<td>0</td>
<td>100</td>
</tr>
  <tr>
<td>four</td>
<td>567</td>
<td>2</td>
<td>1</td>
<td>103</td>
</tr>
  <tr>
<td>two</td>
<td>234</td>
<td>1</td>
<td>1</td>
<td>101</td>
</tr>
  <tr>
<td>three</td>
<td>345</td>
<td>0</td>
<td>1</td>
<td>102</td>
</tr>
  <tr>
<td>five</td>
<td>678</td>
<td>0</td>
<td>0</td>
<td>104</td>
</tr>
</tbody>
</table>

我尝试过的是

$query->addOrderBy(($query->expr()->neq('variant.instock', 0)), 'DESC')
    ->addOrderBy(($query->expr()->eq('variant.instock', 0)) , 'ASC');

最终,这将如下调用SQL查询

SELECT * FROM product ORDER BY instock <> 0 DESC, instock = 0 ASC

并给出这样的输出

<table style="width: 100%;">
<tbody>
<tr>
<th>pid</th>
<th>Lastname</th>
<th>instock</th>
<th>laststock</th>
<th>price</th>
</tr>
  <tr>
<td>two</td>
<td>234</td>
<td>1</td>
<td>1</td>
<td>101</td>
</tr>
    <tr>
<td>four</td>
<td>567</td>
<td>2</td>
<td>1</td>
<td>103</td>
</tr>
  <tr>
<td>one</td>
<td>123</td>
<td>3</td>
<td>0</td>
<td>100</td>
</tr>
  <tr>
<td>three</td>
<td>345</td>
<td>0</td>
<td>1</td>
<td>102</td>
</tr>
  <tr>
<td>five</td>
<td>678</td>
<td>0</td>
<td>0</td>
<td>104</td>
</tr>
</tbody>
</table>

1 个答案:

答案 0 :(得分:0)

您的Sql代码可以如下所示

  SELECT * FROM product ORDER BY case when instock = 0 then 0 else 1 end