How to upgrade next/previous record in mysql - php

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 :)

Related

Update a set of records based on count - MySQL

I have a 100 active records in my table - cars. The user has decided to downgrade their account and is now eligible to only have 5 active records. I need to set the expiration date on 95 records (oldest first) to current timestamp. How do I do this in MySQL - bonus thanks if you include some cakephp hints (but I will thank you for just the SQL hint alone)
Here is what I tried but I get an error message stating that mySQL does not support LIMIT in sub-query
UPDATE cars
SET archived = NOW()
WHERE id NOT IN (
SELECT id
FROM cars
ORDER BY created DESC LIMIT 5
)
The MySQL documentation does not explain why LIMIT clauses in this type of subquery is not supported. However, there is no such limitation on sub-subqueries.
To resolve this issue, lets create another subquery and move the LIMIT clause into it:
WHERE id NOT IN (
SELECT id
FROM (
SELECT id
FROM cars
ORDER BY created
DESC LIMIT 5
)
AS carsInner
)
The innermost query will select only the last five rows, and exists only to satisfy the requirement that the subquery should not contain the limit clause.
The final query looks like:
UPDATE cars
SET `archived` = NOW()
WHERE id NOT IN (
SELECT id
FROM (
SELECT id
FROM cars
ORDER BY created
DESC LIMIT 5
)
AS carsInner
);
See an SQL Fiddle demo here.

how to get next/previous records in mysql based on timestamp

I was wondering how to select next and previous rows from a mysql database with reference to my currently selected row.
I found this question on SO How to get next/previous record in MySQL? but in this case the select is done based on higher and lower id from the reference. I would like to use earlier or later timestamp instead of ids.
There is no reason for using subqueries.
Next:
SELECT * FROM `my_table`
WHERE `the_timestamp` > 123456
ORDER BY `the_timestamp` ASC
LIMIT 1
Prev:
SELECT * FROM `my_table`
WHERE `the_timestamp` < 123456
ORDER BY `the_timestamp` DESC
LIMIT 1
Based on the article you linked to, you can use:
SELECT *
FROM `my_table`
WHERE `the_timestamp` = (
SELECT MIN(`the_timestamp`)
FROM `my_table`
WHERE `the_timestamp` > 1373493634
);
It's formatted for readability. Replace the timestamp I used (1373493634) with the timestamp you want to find the next record after.

UPDATE certain row in SELECTED items with Certain id

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);

Mysql in PHP - how to update only one row in table but with greatest id number

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)

Database update needs FROM clause, but FROM clause causes error

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

Categories