MySQL update a row but a single field - mysql

I update a Table with multiple fields. Now one of the fields may only be updated if another field has a defined value, e.g.:
id | name | image | update
--------------------------------------------------
1 | john | myimage.jpg | 0
2 | ben | yourimage.gif | 1
--------------------------------------------------
Now i walk through all rows and update all fields but the image should only be update if the "update"-flag is set to 1.
If its 0 the existing value should not be overwritten.
Now i tried this:
...
`image` = IF(update = 1, VALUES(`image`),`image`)
...
but its obviously not working because it overwrites the image in every case.

update table
set image = new_value
where update = 1
and id = ?// if you want spacific row, if not ignore this line

If you only want to update the image column Ofer's answer is surely the best. If you'd like to pack the image update into a bigger query, the IF() works as follows:
IF(expression, return this if expression true, return this if expression false)
in your case:
UPDATE table t1
SET
t1.image = IF(t1.update = 1, t1.image, 'new image')

First just fetch the value of update from table by query
Select update from your table where id = 'provide row id'
Then using if else condition by checking value of update fetch fire your update
query
eg.
if($update == 1)
{
echo "Your update query here";
}
else
{
}

Be careful with the name of your column 'update'. It's a reserved word, like you can see below (for updating rows).
I would change it to:
ALTER mytable
CHANGE update update_flag tinyint
and then use the following for updating your rows:
UPDATE mytable
SET image = somevalue
WHERE update_flag = 1
AND id = someid
You only need the last line if you don't want to update all your rows where update_flag is 1.

update your_table
set `image` = case when update = 1
then $newvalue
else `image`
end,
other_column = 'some_value'

Related

UPDATE (B) from (A) if (B) = 0?

I'm learning this for school and I'm confused. I'm trying to copy information between columns in a single table in a single db, all local.
Basically:
(I need to loop through and update all records)
UPDATE `my_records`
SET `realname` = `name`
WHERE `realname` = 0;
SELECT * FROM `my_records` SET `realname` = `name` WHERE `realname` = 0;
It keeps telling me I have a syntax error.
I now see why they are asking me to learn this. Each row in the table is different so when I update all columns some rows change that shouldn't so that's not the end result I'm after. I can try to give an example but this is confusing to me.
DB -> Table -> Row 1 - holds the name of the person -> Row 2 - holds the picture
of the person
Both things have a name (example Row 1 David, Row 2 Flower.JPG)
So I'm guessing they want me to figure out a way to exclude updating the 'real_name' column on Row 2 where the image is a JPG, GIF, or PNG.
I think the final result they are looking for when the table is updated is:
Row 1 'David' 'David'
Row 2 'flower.jpg'
Then this loops over and over again for all the records.
You need to use an UPDATE instead of a SELECT. SELECT statements only return data, they do not modify data.
So, to return the records you will update in the next step:
SELECT `realname`, `name` FROM `my_records` WHERE `realname` = 0;
and then to update those records:
UPDATE `my_records` SET `realname` = `name` WHERE `realname` = 0;
Note that this query will update the entire table, setting any row where the value of realname is equivalent to 0, to the value of that same row's name column.
A few other possibly useful statements:
UPDATE `my_records` SET `realname` = `name` WHERE `realname` = '';
This will affect all rows where realname is equivalent to 'empty string'
UPDATE `my_records` SET `realname` = `name` WHERE `realname` IS NULL;
will affect all rows where realname is NULL

How to update multiple rows with one query with MySQL?

I'm currently running more database queries of update, like the following:
UPDATE table SET status = 1 WHERE id = 3
UPDATE table SET status = 1 WHERE id = 7
UPDATE table SET status = 1 WHERE id = 9
UPDATE table SET status = 1 WHERE id = 18
etc...
Question:
How is it possible to run these queries in one?
UPDATE table SET status = 1 WHERE id in (3,7,9,18,...)
If you need to update some rows on a given list you can use IN()
UPDATE table SET status = 1 WHERE id IN (3, 7, 18);
If instead you need to update all rows just don't add any WHERE conditions
UPDATE table SET status = 1;
Your question is a bit general if you mean how to update multiple rows in one command in general it depends on your queries but if your question is more specific and you need to run 1 single query instead of all above queries you can try this :
UPDATE table SET status = 1 WHERE id IN (3,7,9,18)

Copy values from one column to another in the same table

How can I make a copy values from one column to another?
I have:
Database name: list
-------------------
number | test
-------------------
123456 | somedata
123486 | somedata1
232344 | 34
I want to have:
Database name: list
----------------
number | test
----------------
123456 | 123456
123486 | 123486
232344 | 232344
What MySQL query should I have?
Short answer for the code in question is:
UPDATE `table` SET test=number
Here table is the table name and it's surrounded by grave accent (aka back-ticks `) as this is MySQL convention to escape keywords (and TABLE is a keyword in that case).
BEWARE!
This is pretty dangerous query which will wipe everything in column test in every row of your table replacing it by the number (regardless of it's value)
It is more common to use WHERE clause to limit your query to only specific set of rows:
UPDATE `products` SET `in_stock` = true WHERE `supplier_id` = 10
UPDATE `table_name` SET `test` = `number`
You can also do any mathematical changes in the process or use MySQL functions to modify the values.
try this:
update `list`
set `test` = `number`
BEWARE : Order of update columns is critical
GOOD: What I want saves existing Value of Status to PrevStatus
UPDATE Collections SET PrevStatus=Status, Status=44 WHERE ID=1487496;
BAD: Status & PrevStatus both end up as 44
UPDATE Collections SET Status=44, PrevStatus=Status WHERE ID=1487496;
try following:
UPDATE `list` SET `test` = `number`
If list is table name and test and number are columns
it creates copy of all values from "number" and paste it to "test"
Following worked for me..
Ensure you are not using Safe-mode in your query editor application. If you are, disable it!
Then run following sql command
for a table say, 'test_update_cmd', source value column col2, target
value column col1 and condition column col3: -
UPDATE test_update_cmd SET col1=col2 WHERE col3='value';
Good Luck!
IF Anyone wants to put Condition
UPDATE bohf SET Sq=IDNo WHERE Table = 'AOF' AND FormSq BETWEEN 13 AND 17
update `table`
set `firstcolumn` = `secondcolumn`

Generate GUID in MySQL for existing Data?

I've just imported a bunch of data to a MySQL table and I have a column "GUID" that I want to basically fill down all existing rows with new and unique random GUID's.
How do I do this in MySQL ?
I tried
UPDATE db.tablename
SET columnID = UUID()
where columnID is not null
And just get every field the same
I had a need to add a guid primary key column in an existing table and populate it with unique GUID's and this update query with inner select worked for me:
UPDATE sri_issued_quiz SET quiz_id=(SELECT uuid());
So simple :-)
I'm not sure if it's the easiest way, but it works. The idea is to create a trigger that does all work for you, then, to execute a query that updates your table, and finally to drop this trigger:
delimiter //
create trigger beforeYourTableUpdate BEFORE UPDATE on YourTable
FOR EACH ROW
BEGIN
SET new.guid_column := (SELECT UUID());
END
//
Then execute
UPDATE YourTable set guid_column = (SELECT UUID());
And DROP TRIGGER beforeYourTableUpdate;
UPDATE
Another solution that doesn't use triggers, but requires primary key or unique index :
UPDATE YourTable,
INNER JOIN (SELECT unique_col, UUID() as new_id FROM YourTable) new_data
ON (new_data.unique_col = YourTable.unique_col)
SET guid_column = new_data.new_id
UPDATE once again:
It seems that your original query should also work (maybe you don't need WHERE columnID is not null, so all my fancy code is not needed.
The approved solution does create unique IDs but on first glance they look identical, only the first few characters differ.
If you want visibly different keys, try this:
update CityPopCountry set id = (select md5(UUID()));
MySQL [imran#lenovo] {world}> select city, id from CityPopCountry limit 10;
+------------------------+----------------------------------+
| city | id |
+------------------------+----------------------------------+
| A Coruña (La Coruña) | c9f294a986a1a14f0fe68467769feec7 |
| Aachen | d6172223a472bdc5f25871427ba64e46 |
| Aalborg | 8d11bc300f203eb9cb7da7cb9204aa8f |
| Aba | 98aeeec8aa81a4064113764864114a99 |
| Abadan | 7aafe6bfe44b338f99021cbd24096302 |
| Abaetetuba | 9dd331c21b983c3a68d00ef6e5852bb5 |
| Abakan | e2206290ce91574bc26d0443ef50fc05 |
| Abbotsford | 50ca17be25d1d5c2ac6760e179b7fd15 |
| Abeokuta | ab026fa6238e2ab7ee0d76a1351f116f |
| Aberdeen | d85eef763393862e5fe318ca652eb16d |
+------------------------+----------------------------------+
I'm using MySQL Server version: 5.5.40-0+wheezy1 (Debian)
select #i:=uuid();
update some_table set guid = (#i:=uuid());
Just a minor addition to make as I ended up with a weird result when trying to modify the UUIDs as they were generated. I found the answer by Rakesh to be the simplest that worked well, except in cases where you want to strip the dashes.
For reference:
UPDATE some_table SET some_field=(SELECT uuid());
This worked perfectly on its own. But when I tried this:
UPDATE some_table SET some_field=(REPLACE((SELECT uuid()), '-', ''));
Then all the resulting values were the same (not subtly different - I quadruple checked with a GROUP BY some_field query). Doesn't matter how I situated the parentheses, the same thing happens.
UPDATE some_table SET some_field=(REPLACE(SELECT uuid(), '-', ''));
It seems when surrounding the subquery to generate a UUID with REPLACE, it only runs the UUID query once, which probably makes perfect sense as an optimization to much smarter developers than I, but it didn't to me.
To resolve this, I just split it into two queries:
UPDATE some_table SET some_field=(SELECT uuid());
UPDATE some_table SET some_field=REPLACE(some_field, '-', '');
Simple solution, obviously, but hopefully this will save someone the time that I just lost.
Looks like a simple typo. Didn't you mean "...where columnId is null"?
UPDATE db.tablename
SET columnID = UUID()
where columnID is null
I faced mostly the same issue.
Im my case uuid is stored as BINARY(16) and has NOT NULL UNIQUE constraints.
And i faced with the issue when the same UUID was generated for every row, and UNIQUE constraint does not allow this. So this query does not work:
UNHEX(REPLACE(uuid(), '-', ''))
But for me it worked, when i used such a query with nested inner select:
UNHEX(REPLACE((SELECT uuid()), '-', ''))
Then is produced unique result for every entry.
MYsql
UPDATE tablename SET columnName = UUID()
oracle
UPDATE tablename SET columnName = SYS_GUID();
SQLSERVER
UPDATE tablename SET columnName = NEWID();;
UPDATE db.tablename SET columnID = (SELECT UUID()) where columnID is not null
// UID Format: 30B9BE365FF011EA8F4C125FC56F0F50
UPDATE `events` SET `evt_uid` = (SELECT UPPER(REPLACE(#i:=UUID(),'-','')));
// UID Format: c915ec5a-5ff0-11ea-8f4c-125fc56f0f50
UPDATE `events` SET `evt_uid` = (SELECT UUID());
// UID Format: C915EC5A-5FF0-11EA-8F4C-125FC56F0F50
UPDATE `events` SET `evt_uid` = (SELECT UPPER(#i:=UUID()));
I got this error when using mysql as sql_mode = "". After some testing, I decided that the problem was caused by this usage. When I tested on the default settings, I found that this problem was not there.
Note: Don't forget to refresh your connection after changing the mode.
SELECT CONCAT(SUBSTRING(REPLACE(UUID(),'-',''), 1, 5), SUBSTRING(UPPER(REPLACE(UUID(),'-','')), 4, 5), SUBSTRING('##$%(*&', FLOOR(RAND()*(1-8))+8, 1)) pass
I did this SELECT, five character lower case, five character upper case and one special character.

Is there a fast way to update many records in SQL?

I need to replace more than 20 000 names with new names i created given the CodeID.
For example: I must update all rows that contain "dog" (which has a CodeID of 1) with "cat", and update all rows that contain "horse" (which has a CodeID of 2) with "bird", etc.
1st SQL statement: UPDATE animalTable SET cDescription = "cat" WHERE CodeID = 1
2nd SQL statement: UPDATE animalTable SET cDescription = "bird" WHERE CodeID = 2
These statements work, but i need a faster way to do this because i have over 20 000 names.
Thank you in advance.
Thats the fastest way you can do it.
Or do you want update all records in a single command?
you can do a update with a join (Fixed Syntax... Havent used this one in a while)
UPDATE animalTable
INNER JOIN CodeTable ON animalTable.CodeID = CodeTable.ID
SET animalTable.cDescription = CodeTable.Description_1;
Another option is to split the updates into smaller batches, this will reduce the time the table is locked... But the total time of the updates will take longer (Its just an improvement of precieved Performance) You can do that by updating only certain ID ranges in each batch.
Also you could have that data in a separate table. Since the data is not normalized. Move it away so its more normalized.
You might want to create a temporary table that holds the translation values and update based on that.
For example:
create table #TRANSLATIONS
(
from varchar(32),
to varchar(32)
)
Then, insert the translation values:
insert into #TRANSLATIONS (from,to) values ('cat','dog')
Finally, update based on that:
update MYTABLE
set myvalue = t.to
where myvalue = t.from
from MYTABLE m,
#TRANSLATIONS t
(Untested, off the top of my head).
You could use a CASE statement to update it:
UPDATE animaltable SET cDescription = CASE codeID WHEN 1 THEN 'cat' WHEN 2 THEN 'bird'.... END
Supposind you have a file like this:
1,cat
2,bird
...
I would write a script which reads that file and executes an update for each row.
In PHP:
$f = fopen("file.csv","r")
while($row = fgetcsv($f, 1024)) {
$sql = "update animalTable set cDescription = '".$row[1]."' where CodeID = ".$row[0];
mysql_query($sql);
}
fclose($f);
What you could do to speed it up is to only update those records that don't already have the value you want to assign.
UPDATE animalTable SET cDescription = "cat" WHERE CodeID = 1 AND cDescription != "cat"
This approach makes the command only update those records that are not already 'cat'.
Disclaimer: I hate cats.