I have a long list from database which i want to update a field by name group. i want to update the first 30 to value '1' next 30 to value '2' and so on until the end
Any idea on how to go about it
$sql = mysqli_query($conn,
"UPDATE `tablename` SET `group` = '$value' WHERE id IN (SELECT id FROM tablename ORDER BY id desc LIMIT 0, 30)");
You have run into this limitation of mysql
You cannot update a table and select from the same table in a
subquery.
You could use an update join, but since limits are involved, you would once again run into the same issue. Since only a small number of records are involved, you could do a simple query to get the ids.
SELECT GROUP_CONCAT(id) FROM tablename ORDER BY id desc LIMIT 0, 30
Then use that in the next query
UPDATE `tablename` SET `group` = '$value' WHERE id IN (ids_from_above_query)
If you are worried about concurrent updates, start a transaction.
If your update is a one-time thing (and don't need to optimize it, e.g. do it all in one query), you can simply repeat the following query until you are finished:
update `tablename`
SET `group` = '$value'
where `group` is null
order by id desc
limit 30;
All group-values have to be null (or some other unused value) to begin with, so e.g. use update tablename SET group = null first, if they aren't.
And you probably want to do it all in a transaction.
Related
I've been stuck on this for a while. I'm using PHP, and MySQL. What I'm trying to do is create a query to insert a new value into a column called "counter" starting from the second row all the way for 20 columns. The table needs to be sorted by 'article_id' in order to ensure that all the proper rows are updated.
If you can help me to do it for the 2nd row, I can apply that code to the other ones. So I only need the query to update one column at a time.
Table Structure:
Any thoughts?
As far as I can understand it, you are trying to do something like this:
SET #id = SELECT `article_id` FROM `table` ORDER BY `article_id` ASC LIMIT 1, 1;
UPDATE `table` SET `counter` = 1 WHERE `article_id` > #id ORDER BY `article_id` LIMIT 20;
Where of course table is your table name.
Hello there i would like to use a DELETE statement in Mysql in order to delete all the entries after the 1000th entry, but on the same time ordering the entries by descending order of a column... This is the code i am using:
mysql_query("DELETE FROM 'tblname' WHERE #i IN (1000,ROW_COUNT()) ORDER BY points DESC");
Although no error occurred, it doesnt seem to work for some reason.... i am having trouble in the WHERE clause... can anyone help on that ?
You have quotes around your table name:
mysql_query("DELETE FROM 'tblname' WHERE #i IN (1000,ROW_COUNT()) ORDER BY points DESC");
Replace them with backticks as such:
mysql_query("DELETE FROM `tblname` WHERE #i IN (1000,ROW_COUNT()) ORDER BY points DESC");
Edit: (deleting records)
Try:
mysql_query("DELETE TOP (1000) FROM `tblname` ORDER BY points DESC");
You can also try:
DELETE FROM tablename ORDER BY points DESC LIMIT 1000 *
Assuming this is a column named id:
mysql_query("DELETE FROM tablename WHERE id > 1000");
That would leave the first 1,000 rows and remove every other entry.
A few more examples:
DELETE FROM `table` WHERE `id` < 1000
DELETE FROM `table` WHERE `id` LIMIT 0, 1000
DELETE FROM `table` WHERE ID BETWEEN 1 AND 999
Footnote:
If you are using a variable for your table name (which could be a possibility, without seeing full code), use the following, IF this is the case; many do.
$tblname = "your_table_name";
mysql_query("DELETE FROM `".$tblname."` WHERE #i IN (1000,ROW_COUNT()) ORDER BY points DESC");
You should also consider using mysqli_* functions with prepared statements or PDO. The mysql_* functions are deprecated and will be removed from future releases.
See this tutorial: PDO vs. MySQLi: Which Should You Use?
Also, consult this article on SO: How can I prevent SQL injection in PHP?
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)
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
Everyone familiar with php's mysql_query command, knows that it doesn't allow us to perform more than one query (separated by the ; delimiter) in one call...
My problem is that I wan't to be able to define a user variable in my UPDATE query so that I increment it for each row (kinda like auto increment).
It should look like something as this:
SET #t1=0;
UPDATE `mytable` SET `order` = (#t1:=(#t1+1)) ORDER BY `order` ASC;
My problem is that, since I can't define my variable and then make the update, I can't find a way to set the variable inside the query.
I've tried to define it if it was NULL:
... `order` = (IFNULL( #t1 := ( #t1 + 1 ) , #t1 := 0 )) ...
but it didn't worked since the variable resets at each row it works on.
Anyone familiar with mysql that see's a solution?
Thanks in advance.
Old question but here's an answer anyway:
UPDATE `mytable` SET `order` = (#t1 := IFNULL(#t1, 0) + 1) ORDER BY `order` ASC;
IFNULL(#t1, 0) returns 0 if #t1 doesn't have a value or returns the value of #t1 if it has a value.
So on the first row #t1 is not set and it updates as order = (#t1 := 0 + 1) and on the following rows #t1 already has a value and adds +1 each row.
You could use the mysqli library, it allows for multiple querys in one query using the
mysqli->multiple_query( string $querys);
http://us.php.net/mysqli_multi_query
Going out on a limb, how about...
... `order` = (SELECT `order`+1 FROM `mytable` ORDER BY `order` DESC LIMIT 1)
or something like that as a subquery?... I'm not sure whether the subquery re-runs after each update, but if it does, it should select the previously highest order value and increment it?