简体   繁体   中英

Ordering-by the same column in a table with different sort order based on a condition using querybuilder

I have table, where i need to check a condition while running a select statement on this table, based on the condition i need to change the ordering condition. How to achieve this using query builder (Doctrine). example: table name -> product

<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>

so in this table, i need to first check instock value if it is greater than zero i need to order it in DESC order (instock column). else i need to order in ASC order(instock column). How to do this using query builder?

I need output like this

<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>

What i tried is

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

Eventually this would call SQL query like this below

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

and give output like this

<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>

您的Sql代码可以如下所示

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM