获取数据库中最新添加的记录
我只能通过例子来描述这个问题.. 如果我有此数据,
use-id user-name add-date
---------------------------------------------------
2 sami 17/1/2011
2 sami 18/1/2011
3 alaa 18/1/2011
4 jamal 19/1/2011
我想为每个用户选择最新的行,我希望得到此数据:
use-id user-name add-date
---------------------------------------------------
2 sami 18/1/2011
3 alaa 18/1/2011
4 jamal 19/1/2011
对于每个唯一的用户 ID,我想获取最新添加的记录。如何 ?
I can only describe the question by example..
If I have this data
use-id user-name add-date
---------------------------------------------------
2 sami 17/1/2011
2 sami 18/1/2011
3 alaa 18/1/2011
4 jamal 19/1/2011
I want to select the newest row for each user, I want this data to result :
use-id user-name add-date
---------------------------------------------------
2 sami 18/1/2011
3 alaa 18/1/2011
4 jamal 19/1/2011
for each unique user-id I want to get the newsest added record. how ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种方法是获取每个用户最新记录的日期:
我们将调用该查询
newest_records
,并使用它来仅选择具有最新日期的那些行:编辑:
将它们放在一起(复制/粘贴),我们有:
One way is to get the date of the newest record for each user:
We'll call that query
newest_records
, and use it to select only those rows that have the latest date:Edit:
Putting it all together (copy/paste), we have:
据我所知,
User-Id
决定了User-Name
(User-Id --> User-Name
)。这意味着不会有两个相同的User-Id
具有不同的User-Name
。您的数据通过User-Id
数字 2 清楚地显示了这一点,它们都具有相同的User-Name
(sami
)。因此,进行更简单、更高效的查询是有效的:
注意:MySql 还允许您从组中删除
user-name
现在,显然您的表缺少 标准化。您的表应如下所示:
YourTable(User-Id, Add-Date)
您还应该有另一个表
Users
,应如下所示:Users( User-Id, User-Name)
为了在这个新模式中获得您期望的结果,您应该连接两个表。
As I see it
User-Id
determinesUser-Name
(User-Id --> User-Name
). That means there won't be two equalUser-Id
s with differentUser-Name
s. And your data clearly shows this withUser-Id
number 2, which both have the sameUser-Name
(sami
).So it would be valid to do a simpler and more efficient query:
Note: MySql also allows you to remove the
user-name
from the group byNow, clearly your table is lacking Normalization. Your table should look like this:
YourTable(User-Id, Add-Date)
And you should also have another table
Users
that should look like this:Users(User-Id, User-Name)
And to get the result you're expecting in this new schema you should joing both tables.