[英]Retrieve limited rows from single column from mysql database
I am trying to retrieve only last 3 recently added rows from single column from MySql database. 我试图从MySql数据库的单列中检索最近最后添加的3行。 Please help in this--
请为此提供帮助
my jsp code: 我的jsp代码:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.* "%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title></title>
</head>
<body>
<% Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/eco", "root", "vicky");
PreparedStatement ps = con.prepareStatement("select * from registration");
ResultSet rs=ps.executeQuery();
rs.afterLast();
while(rs.previous()){ %>
<p> <%= rs.getString(2) %> </p>
<%} %>
</body>
</html>
my database structure: 我的数据库结构:
ID username email password
1 vikas vikas5@gmail.com 44
2 Aravind Aravind@gmail.com 12
3 rakesh rakesh@gmail.com 123
4 chandra chnadra@gmail.com 123
5 shiva chinthala@gmail.com 12345
6 sai sai@gmail.com 4321
7 ravi ravi@gmail.com 987654
The ouput getting for me 我的输出
ravi
sai
shiva
chandra
rakesh
Aravind
vikas
but i want output as 但我想输出为
ravi sai shiva
chandra rakesh Aravind
vikas
You need to use Order By with Limit . 您需要使用Order By with Limit 。
Order by ID DESC
sorts the data in descending order based on ID
column. Order by ID DESC
排序Order by ID DESC
根据ID
列以降序对数据进行排序。 LIMIT 3
gets the first 3 rows in the sorted data. LIMIT 3
获取排序数据中的前3行。 Change the following: 更改以下内容:
PreparedStatement ps = con.prepareStatement("select * from registration");
to 至
PreparedStatement ps = con.prepareStatement("select * from registration order by ID desc limit 3");
If you want to get only the last 3 records, then you need to change your query. 如果您只想获取最后3条记录,则需要更改查询。
You have to write a nested query like this: 您必须编写一个嵌套查询,如下所示:
SELECT * FROM (select * from registration ORDER BY ID) registration WHERE rownum <= 3 ORDER BY rownum DESC; SELECT * FROM(从注册ORDER BY ID中选择*)在WHERE rownum <= 3 ORDER BY rownum DESC;
Please refer to the following link for further information: 请参考以下链接以获取更多信息:
https://www.techonthenet.com/oracle/questions/bottom_records.php https://www.techonthenet.com/oracle/questions/bottom_records.php
https://www.techonthenet.com https://www.techonthenet.com
this is very nice and very helpfull site to learn Database and other technology. 这是一个非常不错的网站,对学习数据库和其他技术很有帮助。
i hope it will help you 希望对您有帮助
and also you can do it this query is also work 而且你也可以做到这一点查询也可以
SELECT * FROM registration ORDER BY ID DESC LIMIT 3; SELECT * FROM registration ORDER BY ID DESC LIMIT 3;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.