我有下表:
我需要找到最大product_count
的行。
这是我尝试过的SQL,但未给出正确的结果:
SELECT product_id, MAX(product_count)
GROUP BY product_id
编辑:
SELECT product_id, MAX(product_count) as max_count
FROM
(
SELECT product_id, COUNT(product_id) as product_count
FROM wp_stvp_voting_data
GROUP BY product_id
) as T1
GROUP BY product_id
答案 0 :(得分:3)
一个简单的选择是使用LIMIT
:
SELECT product_id, COUNT(product_id) AS product_count
FROM wp_stvp_voting_data
GROUP BY product_id
ORDER BY COUNT(product_id) DESC
LIMIT 1;
如果您需要解决可能存在多个记录以获取最大商品数量的情况,并且希望返回所有联系,那么我们可以尝试使用子查询:
SELECT product_id, COUNT(product_id) AS product_count
FROM wp_stvp_voting_data
GROUP BY product_id
HAVING COUNT(product_id) = (SELECT MAX(cnt) FROM (
SELECT COUNT(*) AS cnt
FROM yourTable
GROUP BY product_id
) t)
如果您使用的是MySQL 8+,那么我们将可以利用ROW_NUMBER
:
SELECT product_id, product_count
FROM
(
SELECT product_id, COUNT(product_id) AS product_count,
ROW_NUMBER() OVER (ORDER BY COUNT(product_id) DESC) rn
FROM yourTable
GROUP BY product_id
) t
WHERE rn = 1;
如果要把所有领带都放在第一位,请将ROW_NUMBER
替换为RANK
。