I want to select last 50 rows from MySQL database within column named id which is primary key. Goal is that the rows should be sorted by id in ASC order, that’s why this query isn’t working
SELECT
*
FROM
`table`
ORDER BY id DESC
LIMIT 50;
Also it’s remarkable that rows could be manipulated (deleted) and that’s why following query isn’t working either
SELECT
*
FROM
`table`
WHERE
id > ((SELECT
MAX(id)
FROM
chat) - 50)
ORDER BY id ASC;
Question: How is it possible to retrieve last N rows from MySQL database that can be manipulated and be in ASC order ?
You can do it with a sub-query:
SELECT * FROM
(
SELECT * FROM table ORDER BY id DESC LIMIT 50
) AS sub
ORDER BY id ASC;
This will select the last 50 rows from table, and then order them in ascending order.
SELECT * FROM table ORDER BY id DESC LIMIT 50
save resources make one query, there is no need to make nested queries
SELECT * FROM table ORDER BY id DESC, datechat DESC LIMIT 50
If you have a date field that is storing the date (and time) on which the chat was sent or any field that is filled with incrementally (order by DESC) or de-incrementally (order by ASC) data per row put it as second column on which the data should be ordered.
That's what worked for me!!!! Hope it will help!!!!
Use it to retrieve last n rows from mysql
Select * from tbl order by id desc limit 10;
use limit according to N value.
if anyone need this
you can change this into
SELECT
*
FROM
`table`
WHERE
id > ((SELECT
MAX(id)
FROM
chat) - 50)
ORDER BY id ASC;
into
SELECT
*
FROM
`table`
WHERE
id > (SELECT MAX(id)- 50 FROM chat)
ORDER BY id ASC;
select * from Table ORDER BY id LIMIT 30
Notes:
* id should be unique.
* You can control the numbers of rows returned by replacing the 30 in the query
Related
My table has around 10k rows. How can I query select 1 random row of the last 10 added rows? I have a date column that is datetime of when the row was added.
This is one I use to get the last 10 rows:
SELECT id FROM mytable order by date desc LIMIT 10
I know I can do SELECT id FROM mytable ORDER BY RAND() LIMIT 1 but that just choose any random row, not from the last 10 rows.
One method uses a subquery:
SELECT t.*
FROM (SELECT id
FROM mytable
ORDER BY date DESC
LIMIT 10
) t
ORDER BY rand()
LIMIT 1;
This version uses the syntax conventions for MySQL.
You can use select * in the subquery to fetch the whole row.
I am working on an app where users can take online exams and then they need to know their rank on all exams taken in the app.
This is the database table structure:
After taking the exam, I need to get the rank for the specific user (usuario) based on two rows, first row to get the rank must be the bigger (puntuacion) and in case of same (puntuacion) the second row to be taken into account is the smaller (duracion) for an specific exam subject (materia).
I need your help to create the needed query.
You want the results sorted by "puntuacion" and "duracion". That's done with order by
SELECT * FROM your_table ORDER BY puntuacion DESC, duracion ASC
It's not quite clear how you want to sort it, so you may have to switch around ASC with DESC.
If you want to add the row number and have a high enough MariaDB/Mysql-Version (Mysql 8.0) then you can use a window-function: https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html
SELECT
ROW_NUMBER() OVER (ORDER BY puntuacion DESC, duracion ASC) as row,
*
FROM your_table
ORDER BY puntuacion DESC, duracion ASC
Assuming the users are unique (delete DESC if you need to rank by ascending order) :
SELECT * FROM tableName ORDER BY puntuacion DESC, duracion DESC;
Fetch it as an array and get the row with $result[array_search($user)]. Not tested but it should work, let me know.
This is kinda heavy if you have a lot of users (it loads every users every time), but I don't see other solutions.
I have got a working query:
SELECT t.*, #rownum := #rownum + 1 AS rank FROM tb_examenes t, (SELECT #rownum := 0) r WHERE materia = 10 ORDER by puntuacion DESC, duracion ASC
Then I only have to filter for the field I need.
I am not sure if this is possible or not
I have a table with orders and userid
I need to do a SELECT query with ORDER BY the least number of orders of a customer
Example:
userid1 has 10 orders
userid2 has 5 orders
Then SELECT should show userid2 at the top
Thanks in advance
If you have orders as ordersCount i mean as a field which keeps counts of orders then
Select * FROM YourTable order by orders ASC
Else if you have a record for each order then
Select * FROM YourTable Group by UserID order by count(*) ASC;
Apply limit like this
Select *
FROM YourTable
Group by UserID
order by count(*) ASC
limit startIndex, fetchSize;
where startIndex and fetchSize are int that define your limit
You need to group by the userid so you can count orders by user.
SELECT userid, count(1) FROM orders GROUP BY userid ORDER BY count(1) asc
You can accomplish that using GROUP BY and ordering by COUNT().
It would be something like that.
SELECT userid, COUNT(*) qt
FROM orders
GROUP BY userid
ORDER BY qt
If each order is in its own row, however, you need to aggregate them:
SELECT * from MYTABLENAME GROUP BY userid ORDER BY COUNT(*)
Count is what you're looking for
SELECT count(theField) as theCount, *
FROM theTable
GROUP BY theField
ORDER BY theCount
You can select the COUNT of a column and give it a name, then use that name to sort by. Here's an example:
SELECT
p.*,
(SELECT COUNT(o.order_id) FROM orders AS o WHERE p.partron_id=p.patron_id) AS orderCount
FROM
patrons AS p
WHERE
...
ORDER BY
orderCount ASC
UPDATE: Just realized this is only useful if you have orders in a separate table than patrons. Disregard if you are only looking at a single table.
This query expects you to have two tables, a patron table with patron information like name, and a orders table that has a patron_id column that matches the identity column in the patron table.
The advantage to doing this is that you can request patron information at the same time, so you don't need to run two queries in PHP if you're going to use that information.
I am using this query:
SELECT * from likes GROUP BY url ORDER BY count(*) DESC LIMIT 6
to fetch most liked record from my table 'likes'. It is working perfect for fetching most liked content of all time.
But now to I want to select the 6 most liked record from the last 100 records.
What will be the query for it ?
SELECT * FROM (select * from likes order by date desc limit 100) xx
Group by URL order by count(*) limit 6
Obtain the primary keys of the last 100 entries and narrow your query to it. Probably extremely easy if you have auto-increment keys.
SELECT * from likes
GROUP BY url
ORDER BY count(*) DESC
WHERE ID > MAX(ID)-100
LIMIT 6
i want something like this:
SELECT DISTINCT ID from copies WHERE timestamp < 1229444506 ORDER BY CID
the problem is that this one only return ID and i need CID and other columns in the table.
It may be that this is totally wrong for other reason aswell, so i will explain what i need.
I have a table that "record" every row-change in my maintable. This so in the future i will be able to go back in time and see how the main table looked like a certain date in time.
So what i need is a query that ORDER all rows BY CID, WHERE timestamp < 1229444506, AND then DISCTINCT them by ID.
I want to the query to return the first row by ID, when ordered by CID newest first.
Ive tried to get this working with different methods but no luck.
Any suggestions?
I am not sure if I got it correctly, but what about creating a subquery that will just select the columns? You wrote:
"I want to the query to return the first row by ID, when ordered by CID newest first."
So, let's make a subquery:
SELECT id, max(cid) as maxcid FROM copies WHERE timestamp < XX group by id
This will give you the relationship id <=> the CID you want. And now join it:
SELECT copies.* FROM copies, (SELECT id, max(cid) as maxcid FROM copies WHERE timestamp < xxx group by id) x
WHERE copies.id=x.id AND copies.cid=x.maxcid;
SELECT * FROM copies WHERE timestamp < 1229444506 GROUP BY ID ORDER BY CID DESC;
EDIT:
SELECT * FROM copies WHERE timestamp < 1229444506 GROUP BY ID ORDER BY CID;
You can also try:
SELECT * FROM copies WHERE timestamp < 1229444506 GROUP BY ID ASC ORDER BY CID;
Or:
SELECT * FROM copies WHERE timestamp < 1229444506 GROUP BY ID DESC ORDER BY CID;
Does it work?
how can your database know which rows to append to your distinct column? say you haveː
id | name
---+-----
1 | a
1 | b
now the hypothetical query: SELECT DISTINCT id, name FROM table. which name do you expect to show up in your result? a or b?
if that's not a problem you can group your result in mysql by id, but it’s unspecified which name you'll get
SELECT `id`, `name` FROM `copies` WHERE `timestamp` > 123456789 GROUP BY `id` ORDER BY `cid` DESC