简体   繁体   中英

How to count unique values in rows with PHPActiveRecord?

For example, I have table:

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

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

i have working SQL code:

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM