简体   繁体   中英

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. Please help in this--

my jsp code:

<%@ 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 ID DESC sorts the data in descending order based on ID column.
  • LIMIT 3 gets the first 3 rows in the sorted data.

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.

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;

Please refer to the following link for further information:

https://www.techonthenet.com/oracle/questions/bottom_records.php

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM