如何使用PHPActiveRecord计算行中的唯一值?

时间:2022-04-16 22:50:46

For example, I have table:

例如,我有桌子:

id | number
-----------
1  | 1
2  | 1
3  | 1
4  | 2
5  | 2
6  | 3

i need to count unique numbers (1, 2 and 3), that is 3

我需要计算唯一数字(1,2和3),即3

i have working SQL code:

我有工作的SQL代码:

SELECT COUNT(DISTINCT `number`) AS `total` FROM `some_table`

but i don't know how better to do this with PHPActiveRecord

但我不知道用PHPActiveRecord做得更好

1 个解决方案

#1


0  

There is a count() function in phpAR, but you can't make it work with DISTINCT. So, I think the easiest is:

phpAR中有一个count()函数,但你无法使用DISTINCT。所以,我认为最简单的是:

$total = SomeModel::first(['select' => 'COUNT(DISTINCT `number`) AS `total`'])->total;

#1


0  

There is a count() function in phpAR, but you can't make it work with DISTINCT. So, I think the easiest is:

phpAR中有一个count()函数,但你无法使用DISTINCT。所以,我认为最简单的是:

$total = SomeModel::first(['select' => 'COUNT(DISTINCT `number`) AS `total`'])->total;