Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 检索每个组中的最新记录_Mysql_Group By - Fatal编程技术网

Mysql 检索每个组中的最新记录

Mysql 检索每个组中的最新记录,mysql,group-by,Mysql,Group By,我有一张桌子,像这样: 表格新闻 Id Name Other_Columns ------------------------- 1 A data 1 2 A data 2 3 A data 3 4 B data 4 5 B data 5 6 C data 6 我需要找回这样的东西 Group A ---------- data 1 data 2 data 3 Group B

我有一张桌子,像这样:

表格新闻

Id   Name   Other_Columns
-------------------------
1    A       data 1
2    A       data 2
3    A       data 3
4    B       data 4
5    B       data 5
6    C       data 6
我需要找回这样的东西

Group A
----------
data 1
data 2
data 3

Group B
----------
data 4
data 5

Group C
----------
data 6

有人能帮我做一下MySql语句吗?

不太清楚你到底想要什么,但这行吗

select "Group A"
union all
select Other_Columns from news where name = "A"
union all
select "Group B"
union all
select Other_Columns from news where name = "B"
union all
select "Group C"
union all
select Other_Columns from news where name = "C"

这很简单。查询将类似于:

A组:

SELECT Other_Columns FROM news WHERE Name = 'A';
将“B”和“C”替换为“A”,以获得其他组。

应该这样做:

select asdf.Name, asdf.Other_Columns from (
select
if(@prev != q.Name, @rownum:=1, @rownum:=@rownum+1) as rownumber, @prev:=q.Name, q.*
from (
select
Name,
Other_Columns
from
yourTable yt
, (select @rownum:=0, @prev:='') r
order by Id, Name, Other_Columns
)q
)asdf 
where asdf.rownumber <= 5

这将给你5个最新的。格式化数据是在表示层中完成的,如前所述。

是的,很简单:从表中选择*。MySQL不是用来为您格式化数据的。这是在表示层完成的。真的吗?我以为我在MySQL上看到过这样的东西,只是因为你们看到了,并不意味着这是最佳实践。嗯,好吧,然后我会将所有数据发送到数组,然后我会订购它们等等,没有看到你们的评论,你们需要5个最新版本。你应该早一点提到。解决方案并不是那么简单。我需要按名称对所有数据进行分组,然后从每个组中获取5个最新条目。是的,但我需要在一条语句中完成这项工作。而且名字不仅仅是3个A、B、C,甚至可以是10个或更多@亚历克斯很高兴我能帮忙。本网站的最佳实践是,通过单击答案左侧的复选框来接受答案。这样别人就不会浪费时间,因为他们看到问题已经解决了,这是感谢回答者的好方法