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
Related
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");
I need to Select a column with name song_number where id = 2 and then update the second row from the selected rows with 7 for example
what i think that the query i need is something like this but i can't get it work
UPDATE `song` SET `song_number`= 7 WHERE (SELECT `song_number` FROM `song` WHERE `id` = 2 LIMIT 1,1)
any help will be appreciated
edit: i think the problem is mainly in the database structure i made however i found a solution to what i need by making stored procedure http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
so that i can save the selected items in a procedure and then update it
You have to identify which row you want to update. Identification means using a UNIQUE key or the PRIMARY key of the table.
The limitation of MySQL on UPDATE can be lifted by moving the condition from the WHERE to a JOIN:
UPDATE
song AS s
JOIN
( SELECT PK --- the Primary Key of the tba;e
FROM song
WHERE id = 2
ORDER BY ---whatever
LIMIT 1 OFFSET 1
) AS u
ON u.PK = s.PK
SET s.song_number= 7
If the PRIMARY KEY is id, then the above is useless of course. You are doing something wrong.
I doubt it is possible with one query and yet I see no reason in doing it in one query.
Why can't you just select and then update?
I think should be like this:
UPDATE `song` SET `song_number`= 7 WHERE `song_number` = (SELECT `song_number` FROM `song` WHERE `id` = 2 LIMIT 1,1);
I am trying to update fields in my DB, but got stuck with such a simple problem: I want to update just one row in the table with the biggest id number. I would do something like that:
UPDATE table SET name='test_name' WHERE id = max(id)
Unfortunatelly it doesnt work. Any ideas?
Table Structure
id | name
---|------
1 | ghost
2 | fox
3 | ghost
I want to update only last row because ID number is the greatest one.
The use of MAX() is not possible at this position. But you can do this:
UPDATE table SET name='test_name' ORDER BY id DESC LIMIT 1;
For multiple table, as #Euthyphro question, use table.column.
The error indicates that column id is ambiguous.
Example :
UPDATE table1 as t1
LEFT JOIN table2 as t2
ON t2.id = t1.colref_t2
SET t1.name = nameref_t2
ORDER BY t1.id DESC
LIMIT 1
UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table)
This query will return an error as you can not do a SELECT subquery from the same table you're updating.
Try using this:
UPDATE table SET name='test_name' WHERE id = (
SELECT uid FROM (
SELECT MAX(id) FROM table AS t
) AS tmp
)
This creates a temporary table, which allows using same table for UPDATE and SELECT, but at the cost of performance.
I think iblue's method is probably your best bet; but another solution might be to set the result as a variable, then use that variable in your UPDATE statement.
SET #max = (SELECT max(`id`) FROM `table`);
UPDATE `table` SET `name` = "FOO" WHERE `id` = #max;
This could come in handy if you're expecting to be running multiple queries with the same ID, but its not really ideal to run two queries if you're only performing one update operation.
UPDATE table_NAME
SET COLUMN_NAME='COLUMN_VALUE'
ORDER BY ID
DESC LIMIT 1;
Because you can't use SELECT IN DELETE OR UPDATE CLAUSE.ORDER BY ID DESC LIMIT 1. This gives you ID's which have maximum value MAX(ID) like you tried to do. But MAX(ID) will not work.
Old Question, but for anyone coming across this you might also be able to do this:
UPDATE
`table_name` a
JOIN (SELECT MAX(`id`) AS `maxid` FROM `table_name`) b ON (b.`maxid` = a.`id`)
SET a.`name` = 'test_name';
We can update the record using max() function and maybe it will help for you.
UPDATE MainTable
SET [Date] = GETDATE()
where [ID] = (SELECT MAX([ID]) FROM MainTable)
It will work the perfect for me.
I have to update a table with consecutive numbers.
This is how i do.
UPDATE pos_facturaciondian fdu
SET fdu.idfacturacompra = '".$resultado["afectados"]."',
fdu.fechacreacion = '".$fechacreacion."'
WHERE idfacturaciondian =
(
SELECT min(idfacturaciondian) FROM
(
SELECT *
FROM pos_facturaciondian fds
WHERE fds.idfacturacompra = ''
ORDER BY fds.idfacturaciondian
) as idfacturaciondian
)
Using PHP I tend to do run a mysqli_num_rows then put the result into a variable, then do an UPDATE statement saying where ID = the newly created variable. Some people have posted there is no need to use LIMIT 1 on the end however I like to do this as it doesn't cause any trivial delay but could prevent any unforeseen actions from being taken.
If you have only just inserted the row you can use PHP's mysqli_insert_id function to return this id automatically to you without needing to run the mysqli_num_rows query.
Select the max id first, then update.
UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table)
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 :)
What SQL query would I use to display the newest entry?
Details:
id is the primary field. I have other fields but that are not related to when they were added.
ORDER BY SomeColumn DESC
LIMIT 1
or
use the MAX() function
Since you didn't give any details about your table it is hard to answer
SELECT * from yourTable ORDER BY `id` DESC LIMIT 1;
Another (better) way would be to have a "date_added" column (date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP) so you could order by that column descending instead. Dates are more reliable than ID-assignment.
not sure if this is what your looking for but I use mysql_insert_id() after inserting a new row
The auto incremented ID columns are not always the latest records inserted, I've remember really painful experience with this behavior. Conditions where specific, it was mysql 4.1.x at the time and there was almost 1 million records, where 1 out of 3 deleted everiday, and others re inserted in the next 24hours. It made a huge mess when I realize ordering them via ID was not ordering them by age....
Since then, I use a specific column for doing age related sorts, and populating these fields with date = NOW() at each row insert.
Of course it will work to found the latest record as you want, doing an ORDER BY date DESC LIMIT 0,1on your query
SELECT Primary_Key_Field FROM table ORDER BY Primary_Key_Field DESC LIMIT 1
Replace Primary_Key_Field and table obviously :)