如何在mysql查询中按行限制组?

时间:2012-06-15 22:24:25

标签: mysql

这里还有其他问题听起来相似但不是。我有一个返回带有group by的行的查询,我想按行应用总计限制,而不是用于创建组的总行数。

ID    TYPE        COLOR        SIZE
----------------------------------------
1     Circle      Blue         Large
2     Circle      Red          Large
3     Square      Green        Large
4     Circle      Purple       Large
5     Circle      Blue         Small
6     Circle      Yellow       Medium
7     Circle      Black        Large
8     Oval        Blue         Large
9     Circle      Gray         Small
10    Triangle    Black        Large
11    Star        Green        Large
12    Triangle    Purple       Large

SELECT size, type FROM clothes WHERE size = 'large' GROUP BY type LIMIT 0, 5

TYPE       SIZE       ROWS
---------------------------    
Circle     Large      4
Square     Large      1

^^^^ 2已经排空我的限制的行列

TYPE       SIZE       ROWS
---------------------------    
Circle     Large      4
Square     Large      1
Oval       Large      1
Triangle   Large      2
Star       Large      1

^^^^这里我想要什么,限制应用于小组

必须有一些子查询,或者我可以在这里做些什么,但我不知道它。

感谢。

3 个答案:

答案 0 :(得分:7)

这对我有用:

SELECT type, size, COUNT(*) AS rows
FROM clothes
WHERE size = 'large'
GROUP BY type
LIMIT 0, 5

结果:

type      size   rows
------------------------
Circle    Large     4
Oval      Large     1
Square    Large     1
Star      Large     1
Triangle  Large     2

应该在GROUP BY之后应用LIMIT,所以我不明白这个问题。

答案 1 :(得分:3)

SELECT * FROM (
  SELECT id, color, size, type FROM clothes WHERE size = 'large' GROUP BY type 
) AS baseview LIMIT 0, 25

答案 2 :(得分:0)

如何计算有多少?

select color, size, type, count(id) from clothes where size = 'large' group by size, type, color;

我是sql编程的新手,但是这应该返回以下内容,这样你就可以为每种颜色/尺寸/类型组合使用1行,然后获得数量计数。

红色大衬衫4

绿色大衬衫6

绿色大裤子2

依旧......

相关问题