SQL how to write a query to retrieve latest post
I have a database with date and time column, user will enter comment. I want a query to able开发者_如何学JAVA to retrieve latest 10 post.
Select comment from Comment where username = ? and date ...
I not sure how to compare to get latest data? any suggestion
SELECT comment FROM Comment ORDER BY date DESC LIMIT 10
This will order all comments by date, starting with the most recent one and get the last 10 entries. (where "LIMIT" is mySQL, you may need to use "SELECT TOP 10" depending on your server)
Judging from your description ("get latest 10 posts") there's no need to include WHERE username ?
in your query. It would help, if you posted your table structure.
Note my answer is more or less similar to previous ones,only difference being ordering part. (based on your comment to @m.edmondson) The following will order time and date as you want.
Select comment
from Comment
order by Date desc ,time desc LIMIT 10
Also, why you don't have a primary key?
select top 10 comment
from Comment
order by date desc
The easy solutions to the "restrict query to ten rows" problem are very database specific. So, the answers presented so far will tie you to a specific DBMS. If you want a non-generic DBMS specific way to do this, you will need to state the type of DB you are working with.
Update: I see you've added a comment to specify that the type of DB you are using is MySQL. In this case, adding a LIMIT clause to limit your results to ten rows (LIMIT 10
) with a descending order by date (ORDER BY date DESC
) to your query will solve your problem.
精彩评论