Is there an MySQL query which would delete all values from a table, except the latest 20 entries (ordered by id)?
So let's say I have a table notifications, where 1000 notifications reside and I want to keep only latest 20.
If SQL is not enough for this, using php is optional.
I have a few ideas how to do this, but I don't really consider them efficient.
You can find the latest id, store it into local variable and then delete everything below this id:
set #tmp_id := (select id from notifications order by id desc limit 20,1);
delete from notifications where id <= #tmp_id;
I have not ran this, so I apologize if it doesn't work, but according to the SQL syntax for delete this should work.
DELETE FROM notifications ORDER BY id ASC LIMIT ((SELECT COUNT(*) FROM notifications)-20);
$result = $mysqli->query("SELECT ids FROM notifications");
$count = $result->num_rows;
$count -=20;
$result = $mysqli->query("DELETE FROM notifications ORDER BY id ASC LIMIT $count");
Related
I got an odd problem. Whenever I add a new entry to the database it gives it a higher id number, but somehow sees it as a lower number and puts it below the older ones.
And when sorting DESC in PHP I also get this order, does anybody know whats going wrong here?
I use $res = mysql_query("SELECT * FROM data ORDER BY 'id' DESC");to sort them, and it gives the same order as in the pic. (Not sure why i'm being downvoted here but ok..)
Pic:
Your query is:
SELECT * FROM data ORDER BY 'id' DESC
You are sorting by the string 'id', note the syntax highlighting when not within quotes. This means you get them in a random order. Remove the '. If you meant to escape the column id you should use back-ticks:
SELECT * FROM data ORDER BY `id` DESC
When you insert data on the tables, it does not mean that the new number (or the highest) always on the lowest row. It randomly inserts the record. The only way you can sort it when you retrieve the rows in by using ORDER BY clause, example
SELECT *
FROM tableName
ORDER BY ID DESC
So assume that ID is numeric. If you're ID is stored as string then you should convert it to numeric,
SELECT *
FROM tableName
ORDER BY CAST(ID AS SIGNED) DESC
UPDATE 1
It should be
$res = mysql_query("SELECT * FROM data ORDER BY `id` DESC");
not
$res = mysql_query("SELECT * FROM data ORDER BY 'id' DESC");
what you have done was you have surrounded the ID with single quote forcing the server to read it as String and not Numeric
When you are not using any ORDER BY clause, the order in PHPMyAdmin is kind of random. Indeed, new rows could take place of old ones.
I am curious how you sort DESC in PHP though.
Don't absolutely trust in GUI web interface because sometimes (not always) it bugs with session management, however you can run SQL Queries using it.
1- To run a SQL query, click on "SQL" on the navigation bar.
2- Enter your SQL in the box provided.
SELECT *
FROM tableName
ORDER BY ID DESC
3- Click "Go".
So I have a database, and I would like to display the last ten entries.
So far I have tried several ways but run into a couple of issues. I have tried using a for-loop starting at the row count for the database and linking that to the ID, but then of course should I delete an entry the iterations will have data missing. For example if I have deleted lots of entries and have the first entry start at id 20 then if there are only 10 rows it will look to display 10 to 1, which don't exist.
Any thoughts?
You could try, depending on your implementation,
SELECT * FROM `table_name` WHERE conditions ORDER BY `id` DESC LIMIT 10;
Try this :
mysql_connect("localhost","usernm","pwd");
mysql_select_db("database");
$rs=mysql_query("SELECT id,col1,col2,coln FROM table_name WHERE condt ORDER BY id DESC LIMIT 10") or die(mysql_error());
while($row= mysql_fetch_row($rs))
{
print_r($row);
}
I've been trying to figure out how to update the ID of the newest person in my database for 36 hours. It moans about the clients in the FROM clause, but when I remove that clause, the update affects every ID in the whole database.
UPDATE clients SET ID = $id WHERE timestamp = (SELECT MAX(timestamp) FROM clients)
What am I doing wrong?
Replace it with
UPDATE clients SET ID = $id ORDER BY `timestamp` DESC LIMIT 1
PS: this query solves the original task specified in the question "to update the id of the newest person in my database"
You can't update a table using a WHERE condition aggregated from the exact same table.
perhaps you want this:
UPDATE
client
SET
client.[id] = $id
ORDER BY
client.[timestamp] DESC
LIMIT 1
mysql fetch previous or next record order by anyother field name and not by using order by id
select * from table where id > $id order by name asc limit 1
select * from table where id < $id order by name desc limit 1
I am able to get next and previous records but in this case how can i
upgrade next and previous records.
ID Links orderID
14 Google.com 1
15 Yahoo.com 2
20 gmail.com 3
25 facebook.com 4
What about if i use + and - button in front each link to upgrade and downgrade them and then rearrange the menus order by orderID ?
Well, if you really want to do it in a single query, you can use a subquery to find out the ID you need to update. The problem lies in the fact that MySQL cannot update the same table that you're trying to subquery, for obvious data integrity reasons. So you'll need to use some workarounds for that, such as creating a temporary table in a subquery.
UPDATE table AS t
SET [...]
WHERE t.`id` = (select * FROM (select `id` from table where `id` > $id order by `id` asc limit 1) AS sq)
There is absolutely no need to do the two selects.
You can do the following:
UPDATE table SET field='some value' WHERE id=$id+1
UPDATE table SET field='some value' WHERE id=$id-1
There you go :)
I want to make a simple news system using PHP and MySQL, right now I got a working post and read system but there is only one problem, I want it to show the 10 latest news but instead it shows the 10 oldest news.
My question is: Is there a way to make MySQL return the results from the bottom of a table or do I have to first get the number of posts and then limit it to the very last 10 ones?
Here is the insert (title and text is escaped and time is time(), poster is not done yet):
mysql_query("INSERT INTO news (title, poster, text, time) VALUES ('$newstitle', '1', '$newstext', '$time')") or die(mysql_error());
And to retrive it (addnews echos it):
$myqr = mysql_query('SELECT * FROM news LIMIT 10') or die("Error running news query: ". mysql_error());
while($myres = mysql_fetch_array($myqr))
{
addnews($myres['id'], $myres['title'], "admin", date('l jS F Y - H:i:s', $myres['time']), $myres['text']);
}
So, short: I want to read the database backwards, is it possible?
Check out the ORDER BY clause. It allows you to sort rows by a column in ascending or descending order. The following query will return 10 news items, sorted by time in descending order.
SELECT * FROM news ORDER BY time DESC LIMIT 10
Simple, just add an "ORDER BY" clause to your SQL, e.g.
SELECT * FROM news ORDER BY time DESC LIMIT 10
you need to modify your query to sort by the date it was created. something like
SELECT * FROM news order by time DESC LIMIT 10
should work for you. I think its worth noting that if you do not specify an Order by clause, the order in which results are returned is not guaranteed. Right now, you happen to be getting them ordered by the time they were inserted ascending, however you cannot safely assume that will always be the case.
Assuming that id is the primary key:
SELECT * FROM new ORDER BY id DESC LIMIT 10
Use an ORDER BY clause.
Could you not simply Order By time Descending before LIMIT 10?
use
SELECT * FROM news ORDER BY time DESC LIMIT 10
You could also use
SELECT TOP 10 FROM news ORDER BY time DESC
I believe. Not sure if the 'top' clause is SQL Server only, though.