2013-10-28 12 views
6

ho due tabella come segue:Select, contare e dove utilizzando CodeIgniter e mysql

- tblSaler 

    SalerID | SalerName | 
    ----------------------| 
    1  | sothorn | 
    ----------------------| 
    2  | Daly  | 
    ----------------------| 
    3  | Lyhong | 
    ----------------------| 
    4  | Chantra | 
    ----------------------| 

- tblProduct 

ProductID | Product | SalerID | 
--------------------------------| 
1   | Pen  | 3  | 
--------------------------------| 
2   | Book  | 2  | 
--------------------------------| 
3   | Phone | 3  | 
--------------------------------| 
4   | Computer | 1  | 
--------------------------------| 
5   | Bag  | 3  | 
--------------------------------| 
6   | Watch | 2  | 
--------------------------------| 
7   | Glasses | 4  | 
--------------------------------| 

Il risultato che ho bisogno è:

sothorn | 1 
Daly | 2 
Lyhong | 3 
Chantra | 1 

Ho provato questo:

$this->db->select('count(SalerName) as sothorn where tblSaler.SalerID = 1, count(SalerName) as Daly where tblSaler.SalerID = 2, count(SalerName) as Lyhong where tblSaler.SalerID = 3, count(SalerName) as Chantra where tblSaler.SalerID = 4'); 
    $this->db->from('tblSaler'); 
    $this->db->join('tblProduct', 'tblSaler.SalerID = tblProduct.SalerID'); 

risposta

9

È possibile utilizzare questa query per questo

SELECT 
    tblSaler.SalerName, 
    count(tblProduct.ProductID) as Total 
FROM tblSaler 
    LEFT JOIN tblProduct 
    ON tblProduct.SalerID = tblSaler.SalerID 
GROUP BY tblSaler.SalerID 

Ed ecco il record attivo per questo

$select = array(
       'tblSaler.SalerName', 
       'count(tblProduct.ProductID) as Total' 
      ); 
$this->db 
     ->select($select) 
     ->from('tblSaler') 
     ->join('tblProduct','roduct.SalerID = tblSaler.SalerID','left') 
     ->group_by('tblSaler.SalerID') 
     ->get() 
     ->result_array(); 

Demo

USCITA

| SALERNAME | TOTAL | 
|-----------|-------| 
| sothorn |  1 | 
|  Daly |  2 | 
| Lyhong |  3 | 
| Chantra |  1 |   
2

Prova questo

$this->db->select('SalerName, count(*)'); 
$this->db->from('tblSaler'); 
$this->db->join('tblProduct', 'tblSaler.SalerID = tblProduct.SalerID'); 
$this->db->group('SalerID'); 
3

Si prega di provare questo codice. Funziona bene per me e ti aiuterà anche.

$this->db->select('SalerName, count(*)'); 
$this->db->from('tblSaler');   
$this->db->join('tblProduct', 'tblSaler.SalerID = tblProduct.SalerID'); 
$this->db->group_by('tblSaler.SalerID');  
$query = $this->db->get(); 

È possibile ottenere tutta la query SQL utilizzando questa linea di seguito

$query = $this->db->get(); 
echo $this->db->last_query(); 
0
## try this ## 
    $this->db->select($column_name); 
    $this->db->where($column_name,$type); 
    $q=$this->db->get($table_name); 
    $count=$q->result(); 
    return count($count);'