Yii2 : How to write distinct SQL query?

前端 未结 4 1750
遇见更好的自我
遇见更好的自我 2021-01-01 10:55

I want to implement following SQL queries in Yii 2 but with no success.

This should give total number of unique company names:



        
相关标签:
4条回答
  • 2021-01-01 11:16

    Answering my own question I got following working solutions:

    Got the count for unique company_name:

    $my = (new yii\db\Query())
        ->select(['company_name',])
        ->from('create_client')
        ->distinct()
        ->count();
    echo $my;
    

    List of distinct company_name and client_code:

    $query = new yii\db\Query();
    $data = $query->select(['company_name','client_code'])
        ->from('create_client')
        ->distinct()
        ->all();
    if ($data) {
        foreach ($data as $row) {
            echo 'company_name: ' . $row['company_name'] . ' client_code: ' . $row['client_code'] . '<br>';
        }
    }
    
    0 讨论(0)
  • 2021-01-01 11:18

    Try this:

    $total = YourModel::find()->select('company_name')->distinct()->count();
    

    In Search Model:

    public function search($params)
    {
        $query = YourModel::find()->select('company_name')->distinct();
        // or
        $query = YourModel::find()->select(['company_name', 'client_code'])->distinct();
    
        $query->orderBy('id desc');
    
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        // ...
    }
    
    0 讨论(0)
  • 2021-01-01 11:37

    All worked fine

    return Clients::find()->count('DISTINCT(company_name)');
    
    0 讨论(0)
  • 2021-01-01 11:40

    I hope this sample is useful for you

     $names = Yii::$app->db->createCommand('SELECT  count(DISTINCT(company_name)) as name FROM clients')
        ->queryAll();
    

    for access the the data

    foreach ($names as $name){
        echo $name['name'];
    }
    
    0 讨论(0)
提交回复
热议问题