I have the following query which I am trying to run in MySQL. Basically I am trying to work out how to update the corresponding field which isn't null. I know its going to be one of two possible fields but I want to update the one which isn't empty. Maybe I am missing something blindingly obvious, but this is what I've tried thus far:
UPDATE `table`
#SET IF(FieldA IS NULL,FieldB,FieldA) = 1234
#SET IFNULL(FieldA,FieldB) = 1234
WHERE `FieldC` = '5678'
AND (
`FieldA` = '1234'
OR `FieldB` = '1234'
)
I suspect there may be a CASE solution but I'd prefer a shorthand/simple version option if it exists.
(My)SQL has no syntax that allows you to dynamically change the column you want to update, e.g. something like update ... set {PickFieldBaseOnCondition:FieldA|FieldB} = 1234. You have to specify a column there. The moment you start your query, the basic structure of the query (and all fields involved) have to be clear and fixed, only the values can change.
So you need to update both fields in your query if it shall be able to modify two different columns. But you can of course decide to just not modify the content of a field based on its content, e.g. keep it if it is null already:
update `table`
set FieldA = IF(FieldA IS NOT null, 1234, FieldA),
FieldB = IF(FieldB IS NOT null, 1234, FieldB)
where ...
Note that the requirement "update the other field if a field is null" only works if your initial condition that one field is null and one is not null is fulfilled, which you said is given. Otherwise, you should include a test if both fields are null or both fields are not null (in the comparison for the first field), which you could e.g. do with
update `table`
set FieldA = IF(FieldB IS null, 1234, null),
FieldB = IF(FieldB IS NOT null, 1234, FieldB)
where ...
FieldA can now be changed from content to null if both fields are not null (and from null to content if both fields are null), to enforce the condition that exactly one field is not null.
Please also note that IF() is a MySQL-only shorthand for CASE and doesn't work in all databases. You prefered a non-case solution, but it can trivially be rewritten using the sql-standard CASE.
Related
Just notice something weird while was saving 1 as integer into a ENUM('1', '0'). The value got stored as 0.
UPDATE table SET `somefield` = 1 WHERE `id` = 1;
SELECT id, `somefield` WHERE id = 1;
id, somefield
1, 0
Is there any way to make it work? I prefer to don't modify DB.
Also, any information about why this happen and the field is not converted would be very appreciated
When you provide an integer instead of a string for the update value of an enum, it's interpreted as the index of the enum values, not the value.
Enums, like all of SQL, use 1-based indexing, so for your enum index 1 is '1' and index 2 is '0'. Anything else is an error.
That means your update statement should result in a '1', not a zero, so either your table is not defined as you say, or your update statement is not as you say.
See this SQLFiddle proving this.
UPDATE table SET `somefield` = '1' WHERE `id` = 1;
The value needs to be specified as a string.
I'm trying to create a simple table where I insert field and I do some checks in MySql. I've used Microsoft SQL relatively easy. Instead, MySql give evrrytime query errors without even specifying what's going on. Poor MySql software design apart, here's what I'm trying to do:
1 table with 4 fields with an autoincremental autogenerated number to det an ID as primary key
CREATE TABLE `my_db`.`Patients_table` (
`ID_Patient` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`Patient_name` VARCHAR( 200 ) NOT NULL ,
`Recovery_Date` DATETIME NOT NULL ,
`Recovery_count` INT NOT NULL
) ENGINE = MYISAM
a simple stored procedure to insert such fields and check if something exist before inserting:
CREATE PROCEDURE nameInsert(IN nome, IN data)
INSERT INTO Patients_table (Patient_name,Recovery_Date) values (nome,data)
IF (EXISTS (SELECT Recovery_count FROM Tabella_nomi) = 0) THEN
INSERT INTO (Patients_table (Recovery_count)
ELSE
SET Recovery_count = select Recovery_count+1 from Patients_table
END
this seems wrong on many levels and MySQL useless syntax checker does not help.
How can I do this? Thanks.
There seems to be a lot wrong with this block of code. (No offense intended!)
First, Procedures need to be wrapped with BEGIN and END:
CREATE PROCEDURE nameInsert(IN nome, IN data)
BEGIN
...[actually do stuff here]
END
Second, since your table is declared with all fields as NOT NULL, you must insert all fields with an INSERT statement (this includes the Recovery_Date column, and excludes the AUTO_INCREMENT column). You can add DEFAULT CURRENT_TIMESTAMP to the date column if you want it to be set automatically.
INSERT INTO Patients_table (Patient_name,Recovery_Date) values (nome,data)
Third, what exactly is your IF predicate doing?
EXISTS (SELECT Recovery_count FROM Tabella_nomi) = 0
If you want to check if a row exists, don't put the = 0 at the end. Also, Tabella_nomi isn't declared anywhere in that procedure. Also, your SELECT statement should have a WHERE clause, since I'm assuming you want to select a specific row (this is going to select a result set of all recovery_counts).
Fourth, the second INSERT statement seems a little messy. It should look more like the first INSERT, and keep the point I made above in mind.
INSERT INTO (Patients_table (Recovery_count)
Fifth, the ELSE statement
SET Recovery_count = select Recovery_count+1 from Patients_table
Has some problems too. SET is meant for setting variables, not values in rows. I'm not 100% sure what your intent is from this statement, but it looks like you meant to increment the Recovery_count column of a certain row if it already exists. In which case, you meant to do something like this:
UPDATE Patients_table SET Recovery_count = Recovery_count+1 WHERE <conditional predicate>
Where the conditional predicate is something like this:
Patients_name = nome
Try these things, and look at the errors it gives you when you try to execute the CREATE STATEMENT. I bet they're more useful then you think!
I would like to perform an UPDATE in MYSQL in which I take a field value, add a constant and save the new value in the same field.
Let's assume that we have a column called OldValue in a table called aTable.
Pseudocode could be:
UPDATE aTable SET OldValue = OldValue + 220 WHERE someField = someValue
Do you have any idea on how I could do that? I would like to use a single query (on some administration panel) without making a php script. (Of course, in that case the answer is quite simple.)
Your code will work.
See it working in SQLFiddle.
I used your exact query verbatim, except for substituting a real value for "someValue".
Here is a working example using Pseudocode from original question itself.
UPDATE `table1` SET `field1` = `field1` - 18, `field2` = `field2` + 16 WHERE n_id IN (111,222,333) OR form IN ('Digital Editing','Studio Room') AND location_id LIKE ('%home-page10%')
I have a very large table with two INT columns that are null on Default. This is a problem because since they are INT fields, it would help in many cases if they were originally set to 0.
So my questions are, is there a way I can UPDATE and INCREMENT(+1) these fields while they are like this (null on Default)? BTW.. I didn't have luck so far, it seems increment only works when the default=0
..or is my only option to Change the Default to none from null
UPDATE TableName SET column = IFNULL(column, 0) + 1 WHERE ...
More info on IFNULL. It returns the first argument if it is not NULL, the second otherwise.
Try setting the field as NOT NULL to get away with the problem so that default value of 0 is used instead of null. The other option is to set column as zero whenever it is null.
UPDATE TableName SET FieldName = '0' WHERE FieldName IS NULL
Other alternative would be to issue IFNULL to return 0 in case the column is null and then incrementing the column.
UPDATE TableName SET FieldName = IFNULL(FieldName,0)
The SQL standard would be to use COALESCE(); this has been available in MySQL since version 3.23 (which was released into production in 2001):
UPDATE mytable
SET mycolumn = COALESCE(mycolumn, 0) + 1
WHERE my_other_columns = ...
I can't see any reason to choose IFNULL() over COALESCE() here.
Hope this helps.
I've looked all over the internet for my answer, and perhaps I'm just doing things wrong. I have a column in my MySQL table that I need to replace all the NULL values with a text string in my SQL Query using phpMyAdmin. I don't want the output to come out that way, I want to actually replace the null values with the text string.
I've tried
UPDATE `tablename` SET fieldname = replace (fieldname, "", "textstring")
I've read up on
SELECT ISNULL(field,"replacetext)
But this only shows the output, but doesn't actually replace it in the table.
I can't figure this out, and I've wasted so much time trying to find an answer.
update tablename set fieldname = "textstring" where fieldname is null;
Have you tried
UPDATE `tablename` SET fieldname = '' where fieldname is null