SELECT id HAVING id 的最大计数

2023-10-26数据库问题
4

本文介绍了SELECT id HAVING id 的最大计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有一个带有 item_id 和 color_id 的产品表.我正在尝试使用最多的非空实例获取 color_id.

Have a products table with item_id and color_id. I'm trying to get the color_id with the most non-null instances.

这失败了:

SELECT color_id 
  FROM products 
 WHERE item_id=1234 
 GROUP BY item_id 
HAVING MAX(COUNT(color_id))

Invalid use of group function

这个

SELECT color_id, COUNT(color_id)
  FROM products 
 WHERE item_id=1234 
 GROUP BY item_id

退货

color_id count
1, 323
2, 122
3, 554

我正在寻找 color_id 3,它拥有最多的实例.

I am looking for color_id 3, which has the most instances.

是否有一种快速简便的方法无需 2 次查询即可获得我想要的东西?

Is there a quick and easy way of getting what I want without 2 queries?

推荐答案

SELECT color_id AS id, COUNT(color_id) AS count 
FROM products 
WHERE item_id = 1234 AND color_id IS NOT NULL 
GROUP BY color_id 
ORDER BY count DESC
LIMIT 1;

这将为您提供 color_id 和该 color_id 的计数,按计数从最大到最小排序.我想这就是你想要的.

This will give you the color_id and the count on that color_id ordered by the count from greatest to least. I think this is what you want.

为了您的编辑...

SELECT color_id, COUNT(*) FROM products WHERE color_id = 3;

这篇关于SELECT id HAVING id 的最大计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Mysql目录里的ibtmp1文件过大造成磁盘占满的解决办法
ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致...
2025-01-02 数据库问题
151

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12