How to insert attribute to json string in mysql? - mysql

I had a json string in mysql database like following.
{"name":"Georg","position":"Manager"}
I need to add another attribute like "date_of_birth":"1989-06-08"

You can also use JSON_INSERT function:
SELECT JSON_INSERT(#`json`, '$.date_of_birth', '1989-06-08');
See dbfiddle.

You could try using a replace() function on the json string
select REPLACE ( column_name, "}", ', "date_of_birth":"1989-06-08"}')
from my_table
or for update the value in you table
UPDATE my_table
SET column_name = REPLACE ( column_name, "}", ', "date_of_birth":"1989-06-08"}')

Related

concatenate a string for all column values in sql update

I have a component table which has id, query columns. I want to concatenate a string type=bug to the query column for all values. Can it be done using update statement?
udpate dbname.tablename set query=query+"some_string", wiil this work?
If i understand correctly, you can do this with CONCAT(value, ' type=bug') at every field like :
UPDATE `col` SET `col1` = CONCAT(col1, ' type=bug'), SET `col2` ...
SELECT CONCAT(Id,' string') AS 'Column' FROM Table.
UPDATE TABLE SET COLUMN = CONCAT(Id, ' string')
OR
SELECT (Id + 'string') AS 'Column' FROM Table.
UPDATE TABLE SET COLUMN = (Id + 'String')

Format values on entire column SQL

I have a column which has values of format "01-01-2012" and I need to change it to "01.01.2012". I have to do the same for all the entries of that coloumn.
Could you please suggest a way to do it? I need a general SQL statement.
Thanks
Try this using REPLACE:
update tablename set column_name=REPLACE(column_name,'-','.')
One way to do this would be to use a basic UPDATE statement. In this case, you would update your entire table and for each row, set the value of the column to the formatted value. The basic outline would be like so:
UPDATE [TableName]
SET [ColumnName] = [FormattingExpression]
An example of [FormattingExpression] could be:
REPLACE ([ColumnName], '-' , '.' )
This would replace all instances of '-' with '.' for the values in the [ColumnName] column of your [TableName] table.
WITH TEST_DATA AS (
SELECT '12-12-2012' AS mydate FROM DUAL UNION ALL
SELECT '07-23-2013' FROM DUAL
)SELECT REPLACE(mydate, '-', '.') mynewdate
FROM TEST_DATA
Just replaced the - with .
REPLACE ( '01-01-2012' , '-' , '.' )
Try str_to_date
UPDATE `table` SET `date_col` = str_to_date(`date_col`,'%d.%m.%Y')
STR_TO_DATE(str,format)
update table_name set column_name = replace (column_name , '-' , '.' );

How do I remove all spaces from a field in a mysql database in an update query?

What would be the proper syntax used to run an update query on a table to remove all spaces from the values in a column?
I have a user table that had user names with spaces imported into it & I need to remove the spaces. i.e. "john smith sr." needs to be "johnsmithsr."
there are about 500+ occurrences.
You could try something like this:
UPDATE `table` SET `column` = REPLACE( `column` , ' ' , '' )
UPDATE <table>
SET name = REPLACE(name, ' ', '') ;
500+ occurences is not that much so this should execute in no time
Try this
update table_name set column_name = replace(column_name, ' ', '');
The second argument will be replaced by the third argument.
I think this is what we are looking for
SELECT some_columns FROM table_name WHERE REPLACE(col_name, ' ', '') LIKE 'some string';
This is probably your answer:
SELECT replace(col_name , ' ','') FROM table_name;

mySQL to replace all strings no matter field name?

I have this query but I want to change the strings in every field_name found instead of manually changing this.
How I can do this ?
update TABLE_NAME
set FIELD_NAME = replace(FIELD_NAME, ‘find this string’, ‘replace found string with this string’);
Then you have to specify all fieldnames. Example
UPDATE tableName
SET field1 = REPLACE(field1, 'oldstring', 'newstring'),
field2 = REPLACE(field2, 'oldstring', 'newstring'),
field3 = REPLACE(field3, 'oldstring', 'newstring'),
fieldN = REPLACE(fieldN, 'oldstring', 'newstring')
You may use information_schema.columns to build a query for each column
SELECT CONCAT( 'Update table ', table_name,
' set ', column_name, ' = replace(',column_name,', \‘find this string\’, \‘replace found string with this string\’); ')
FROM information_schema.columns
WHERE table_name = '<TableName>'`
This will generate update statements for all of the columns in the table (will save you time and effort to write column names manually).

INSERT INTO ... SELECT without detailing all columns

How do you insert selected rows from table_source to table_target using SQL in MySQL where:
Both tables have the same schema
All columns should transfer except for the auto-increment id
Without explicitly writing all the column names, as that would be tedious
The trivial INSERT INTO table_target SELECT * FROM table_source fails on duplicate entries for primary key.
Either you list all of the fields you want in the insert...select, or you use something else externally to build the list for you.
SQL does not have something like SELECT * except somefield FROM, so you'll have to bite the bullet and write out the field names.
Column names have to be specified -
INSERT INTO table_target SELECT NULL, column_name1, column_name2, column_name3, ...
FROM table_source;
Just pass NULL as a value for the auto-increment id field.
Of course, primary key must be unique. It depends on what you want to achieve, but you could exclude rows with a primary key that already exists.
INSERT INTO table_target SELECT * FROM table_source
WHERE table_source.id NOT IN (SELECT id FROM table_target)
UPDATE: since you also need the extra rows, you should resolve the conflict first, does table_source have relationships? If not you could change those keys:
UPDATE table_source SET id = id + 1000
WHERE id IN (SELECT id FROM table_target)
Where 1000, is a constant, big enough so they go after the end of your table.
Tedious but safe and correct.
Writing INSERT statements without providing a list of columns leads to code that's hard to debug and, more importantly, very fragile code that will break if the definition of the table is changed.
If you absolutely can't write the column names out yourself then it's relatively easy to build a tool into your code that will create the comma-separated list for you.
This is my final solution to mass update with 'replace insert' command.
SET ##session.group_concat_max_len = ##global.max_allowed_packet;
SET #schema_db = 'db';
SET #tabl = 'table';
SET #cols = (SELECT CONCAT('`',GROUP_CONCAT(COLUMN_NAME SEPARATOR '`, `'), '`') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = #schema_db AND TABLE_NAME = #tabl GROUP BY TABLE_NAME);
SET #Querystr = CONCAT('REPLACE INTO ',#schema_db,'.',#tabl,' SELECT ', #cols,' FROM import.tbl_', #tabl);
PREPARE stmt FROM #Querystr;
EXECUTE stmt;
I think you could use syntax like:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
REF: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Hope it helps
INSERT IGNORE just "bypass" the duplicate rows.
http://dev.mysql.com/doc/refman/5.5/en/insert.html
You can probably do it with prepared statements.
PREPARE table_target_insert FROM 'INSERT INTO table_target SELECT ? FROM table_source';
SET #cols:='';
SELECT #cols:=GROUP_CONCAT(IF(column_name = 'id','NULL',column_name) separator ",") FROM information_schema.columns WHERE table_name='table_source';
EXECUTE table_target_insert USING #cols;
It seems as if columns can not be given as a place holder in a MySQL Prepared Statement. I have compiled the following solution for testing:
SET #schema_db = 'DB';
SET #table = 'table';
SET #cols = (SELECT CONCAT(GROUP_CONCAT(COLUMN_NAME SEPARATOR ', '), "\n") FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = #schema_db AND TABLE_NAME = #table GROUP BY TABLE_NAME);
SET #Querystr = CONCAT('SELECT',' ', #cols,' ','FROM',' ',#schema_db,'.',#table,' ', 'Limit 5');
PREPARE stmt FROM #Querystr;
EXECUTE stmt;
You can use dynamic query:
DECLARE #Columns VARCHAR(MAX)=''
DECLARE #Query VARCHAR(MAX)=''
SELECT
#Columns = ISNULL(#Columns +',', '') + T.COLUMN_NAME
FROM
(
select name as COLUMN_NAME from sys.all_columns
where object_id = (select object_id from sys.tables where name = 'Source_Table')
and is_identity = 0
)T
set #Query = 'insert into Target_Table (' + SUBSTRING(#Columns,2 , 9999) + ') select ' + SUBSTRING(#Columns,2 , 9999) + ' from Source_Table';
PRINT #Query
EXEC(#Query)
The easiest way to do it is to use phpmyadmin to write the list of columns, then to change it as needed, in the example below I want to duplicate row with id=1078 and in this table I have id unique auto increment and alias unique.therefore I created my query as follow, with id & alias replaced by a desired value. and it worked like a charm.
INSERT INTO sy3_menuselect 1079, menutype, title, "alias", note, path, link, type, published, parent_id, level, component_id, checked_out, checked_out_time, browserNav, access, img, template_style_id, params, lft, rgt, home, language, client_id from sy3_menuwhere id=1078
Alternatively, to auto increment id, use the following Join statement:
INSERT INTO sy3_menuselect *
from (SELECT MAX(id+1 )from sy3_menu)a
join (select menutype, title, "alias", note, path, link, type, published, parent_id, level, component_id, checked_out, checked_out_time, browserNav, access, img, template_style_id, params, lft, rgt, home, language, client_idfrom sy3_menuwhere id=1079)b