php Yii2:如何编写不同的 SQL 查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31361571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:24:17  来源:igfitidea点击:

Yii2 : How to write distinct SQL query?

phpmysqlyii2

提问by JKLM

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

我想在 Yii 2 中实现以下 SQL 查询,但没有成功。

This should give total number of unique company names:

这应该给出唯一公司名称的总数:

SELECT count(DISTINCT(company_name)) FROM clients

And this should display company_namewith client codeand id(PK):

这应该company_nameclient code和显示id(PK)

SELECT (DISTINCT(company_name,client_code)) FROM clients

How to achieve this?

如何实现这一目标?

采纳答案by JKLM

Answering my own question I got following working solutions:

回答我自己的问题,我得到了以下可行的解决方案:

Got the count for unique company_name:

得到了 unique 的计数company_name

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

List of distinct company_nameand client_code:

不同company_name和列表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>';
    }
}

回答by Muhammad Shahzad

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,
    ]);
    // ...
}

回答by scaisEdge

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'];
}

回答by user2382679

All worked fine

一切正常

return Clients::find()->count('DISTINCT(company_name)');