+--------+-------+
| client | price |
+--------+-------+
| 54 | 25 |
| 648 | 35 |
| 54 | 10 |
| 648 | 8 |
| 54 | 25 |
| 648 | 35 |
+--------+-------+
上面就是我的表模式是如何设置的,我想计算每个client
最频繁的price
值,例如。
+--------+-------+
| client | price |
+--------+-------+
| 54 | 25 |
| 648 | 35 |
+--------+-------+
我很难在MySQL中实现这一点。 我用PHP这样做过:
$clientPrices = $this->database->select('design', [
'clientid',
'price'
]);
$pricesByClients = [];
foreach ($clientPrices as $value) {
$pricesByClients[$value['clientid']][] = $value['price'];
}
foreach ($pricesByClients as $key => $value) {
$priceCount = array_count_values($value);
$mode = array_search(max($priceCount), $priceCount);
$pricesByClients[$key] = $mode;
}
return $pricesByClients;
但是,这是缓慢的,我希望如果我可以使这一点效率或做它在SQL。
不幸的是,MySQL没有计算模式()
的内置函数。
如果您使用的是MySQL8.0,则可以使用窗口函数和聚合:
select client, price
from (
select client, price, rank() over(partition by client order by count(*) desc) rn
from mytable
group by client, price
) t
where rn = 1
在早期版本中,and选项使用having
子句和相关子查询进行筛选
select client, price
from mytable t
group by client, price
having count(*) = (
select count(*)
from mytable t1
where t1.client = t.client
group by t1.price
order by count(*) desc
limit 1
)
对于MySQL8.0+,可以使用row_number()窗口函数:
select t.client, t.price
from (
select client, price,
row_number() over (partition by client order by count(*) desc) rn
from tablename
group by client, price
) t
where t.rn = 1;
对于以前的版本,您可以使用相关子查询:
select distinct t.client, t.price
from tablename t
where (t.client, t.price) = (
select client, price
from tablename
where client = t.client
group by client, price
order by count(*) desc
limit 1
);