我有一个MySql表,有两列,分类和名称。我有4个独特的类别值,此表中有数千条记录。但所有这些记录都属于表格中的4个类别。
现在,我想要的是作为输出,我应该得到每个类别的2个结果,即第一个类别的2个结果,然后是下一个类别的2个结果,依此类推。
单个查询是否可以?
答案 0 :(得分:0)
set @num := 0, @cat := '';
select category,name
@num := if(@cat = category, @num + 1, 1) as row_number,
@cat := category as dummy
from MyTable
group by cateogry, name
having row_number <= 2;
答案 1 :(得分:-1)
这个怎么样?
SELECT * FROM your_table WHERE category = 1 LIMIT 2
UNION
SELECT * FROM your_table WHERE category = 2 LIMIT 2
UNION
SELECT * FROM your_table WHERE category = 3 LIMIT 2
UNION
SELECT * FROM your_table WHERE category = 4 LIMIT 2