简体   繁体   中英

how to select record of particular id if not availabe then select by default record

I have one table

<table style="width:100%">
    <tr>
      <th>serving_name</th>
      <th>price</th>
      <th>store_id</th>
    </tr>
    <tr>
      <td>M</td>
      <td>20</td>
      <td>0</td>
    </tr>
    <tr>
      <td>M</td>
      <td>10</td>
      <td>1</td>
    </tr>
</table>

Select record where store_id = 1 if store_id 1 is not available then select 0 store_id record

How it is possible

If you are looking for a query based on a condition then you can do this:

$this->db->select('whatever')->from('your_table');
if ($store_id == 1){ 
    $this->db->where('store_id', 1)
}else if($store_id == $something_else){ 
    // magic 
}
$query = $this->db->get();

If $store_id 0 is your template, and all other values are numeric and greater than 0, then do it in your SQL via where , order by and limit clauses.

select * from store_table where store_id=42 or store_id=0 order by store_id desc limit 0,1

Use your chosen framework's query engine, or do your own DB interface class/function with either the mysqli class/function family, or PDO . If you go that route, then be sure to use prepared statements.

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