Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 : How to write distinct SQL query?

Tags:

php

mysql

yii2

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

This should give total number of unique company names:

SELECT count(DISTINCT(company_name)) FROM clients 

And this should display company_name with client code and id(PK):

SELECT (DISTINCT(company_name,client_code)) FROM clients 

How to achieve this?

like image 605
JKLM Avatar asked Jul 11 '15 20:07

JKLM


2 Answers

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,     ]);     // ... } 
like image 178
Muhammad Shahzad Avatar answered Sep 27 '22 23:09

Muhammad Shahzad


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>';     } } 
like image 31
JKLM Avatar answered Sep 27 '22 23:09

JKLM