Replace string in column value MYSQL - mysql

Hi i have a table named data_table with columns ID | DATA
Id is integer and Data stored like this:
a:19:{s:10:"store_name";s:9:"STORENAME";s:6:"social";a:7:{s:2:"fb";s:0:"";s:7:"twitter";s:0:"";s:9:"pinterest";s:0:"";s:8:"linkedin";s:0:"";s:7:"youtube";s:0:"";s:9:"instagram";s:0:"";s:6:"flickr";s:0:"";}s:7:"payment";a:2:{s:6:"paypal";a:1:{i:0;s:5:"email";}s:4:"bank";a:0:{}}s:5:"phone";s:0:"";s:10:"show_email";s:2:"no";s:7:"address";a:6:{s:8:"street_1";s:0:"";s:8:"street_2";s:0:"";s:4:"city";s:0:"";s:3:"zip";s:0:"";s:7:"country";s:0:"";s:5:"state";s:0:"";}s:8:"location";s:0:"";s:6:"banner";i:0;s:4:"icon";i:0;s:8:"gravatar";i:0;s:14:"show_more_ptab";s:3:"yes";s:9:"store_ppp";i:12;s:10:"enable_tnc";s:3:"off";s:9:"store_tnc";s:0:"";s:23:"show_min_order_discount";s:2:"no";s:9:"store_seo";a:0:{}s:24:"dokan_store_time_enabled";s:2:"no";s:23:"dokan_store_open_notice";s:0:"";s:24:"dokan_store_close_notice";s:0:"";}
Also i have another table named user_stores ID | STORE
Id is integer and store is string format.
I want to make trigger on update when table user_stores change some store name then change the a s:9:"STORENAME
s:9 is the length of the value, in our example is STORENAME

Assuming you're using MySQL, you can create a trigger on the user_stores table to update the data_table when a store name changes. Here's an example:
CREATE TRIGGER update_storename_trigger
AFTER UPDATE ON user_stores
FOR EACH ROW
BEGIN
UPDATE data_table
SET DATA = REPLACE(DATA, CONCAT('s:', LENGTH(OLD.STORE), ':"', OLD.STORE, '"'), CONCAT('s:', LENGTH(NEW.STORE), ':"', NEW.STORE, '"'))
WHERE DATA LIKE CONCAT('%s:', LENGTH(OLD.STORE), ':"', OLD.STORE, '";%');
END;
This trigger will be executed after the user_stores table is updated and will update the DATA column of the data_table if the store name has changed. The REPLACE function is used to replace the old store name with the new store name in the serialized data stored in the DATA column. The WHERE clause is used to search the data table rows that contain the previous store name in the serialized data.
Note that this trigger assumes that the serialized data in the DATA column is in the serialized format. If the data is in a different format, the trigger will have to be modified.

The final answer who works is:
BEGIN
UPDATE data_table as b
SET b.DATA = CONCAT(SUBSTRING_INDEX(b.STORE, 'store_name', 1),'store_name\";s:',LENGTH(new.STORE),':\"',new.STORE,'\";s',SUBSTRING_INDEX(b.STORE, SUBSTRING_INDEX((SUBSTRING_INDEX(b.STORE, 'store_name', -1)), ':',3), -1))
WHERE b.ID=new.ID
END;

Related

update data in one table with the values from another table

I have 2 tables, shows and show_photo
shows structure:
show_photo structure:
What i want to do is update show_photo.modified column with show.year
This is what i tried but nothing gets updated.
UPDATE show_photo t2
JOIN shows t1 ON t1.id = t2.show_id
SET t2.modified = t1.year;
Converting my comment to an answer:
Change the column type from TIMESTAMP to VARCHAR first, run the
UPDATE query; and again change the data type from VARCHAR to INT
Your current table has modified column set to TIMESTAMP. But, you're trying to update its values to integers, which will fail.

Split string in Mysql by colon and update a table record

I have created a table (Table A), which has a column (Column A) which stores values like this
Example:
ASUNMI:GI:PI:INP:EDM:20141001:NO34W:DERERTBYDAY14:NSW
ASUNMI:GI:PI:HME:EDM:20140929:EO23M:WIERTNACAR:VICETC
I need to split this string and place the data in different columns.
Example:
Column2=ASUNMI
Column3=GI
Column4=PI
Column5=INP
Column6=EDM
I need to split the above string based on colons(:).the no of colons in each field could differ hence I cannot use the
substring_index(çolumn,':',-2) property
I need to then use this to update a table
this is a good link please check this out
if you want to update TableA you can write
UPDATE `TableA` SET `columName` = (SELECT SPLIT_STR(columnName, ':',1) as ColumnName from tableName)
or
UPDATE `TableA` SET `columName` = (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(columName,':',1),':',-1) AS columName FROM tableName)

Trigger on MySQL tables with variable?

I need to create in MySQL trigger on such schema:
mail
oid id
varchar name
varchar reference
adress_mail
oid id
oid id_mail
oid id_adress
adress
oid id
varchar name
after something is inserted into adress_mail it is updating 'mail.reference' with value like every 'adress.name' for example:
I am inserting adress_mail with (1,5,6) and (1,5,7) so trigger will update 'mail.reference' with values from 'adress.name where adress.id = 6' and 'adress.name where adress.id = 7'
Q: The whole problem is how to loop on adress_mail table and get all
'adress.name' in 1 varchar and then just update 'mail.reference' with
that value?
I can setup something like var (variable) in trigger and then collect all results from select?
PS 'mail.reference' it's varchar row to improve some searching feature of application, because I don't have possibility to loop on 'adress_mail' table.
Just don't do that ! You are using an sql data base, and the main idea of it is table relations, so when you'll have to look for data from address linked to mail, perform a select with joins on address_mail.

Computed field value based on other column while insertion

I have a table where I have an ID column(primary key auto increment) and one more column for name.
I want to fill name column's value automatically while insertion based on generated ID column value in format
<IDColumnValue>_School
I am aware of the two ways to do this
using trigger
inserting the row first and then update its column value based on the inserted row id column value
But actually I want to make this field Non Nullable but to use the second option I will have to make it nullable.
Is there any direct way to do this while inserting row so that I can have the field non nullable?
As I said in the comment, you can use a temporary value for the name column. You can use a request like :
INSERT INTO `table` VALUES('', 'name') /*let's assume name is the real name you want to insert*/
I'm not sure then how to use a trigger, but you may want to write something like this :
delimiter #
CREATE TRIGGER update_name_after_insert INSERT ON `table`
for each row
begin
update `table` set name = CONCAT_WS("_", id, name)
end#
It work for firebird but I think it must work in MySQL because MySQL have new/old operators. Bellow trigger for table XYZ with fields B and C (not null).
CREATE OR ALTER trigger xyz_bi0 for xyz
active before insert position 0
AS
begin
new.c=new.b||' some text';--this construction must work in MySQL
end

How to convert a varchar column type to date type without losing the dates

I am looking for a way to change the datatype of a column. Currently, in my database, the date columns types were defined as varchar and I need to convert them back to the date type.
Any idea how to do it?
You will need to adapt this based your your exact table structure but something like;
CREATE TABLE temp (startdate varchar(255), stuff varchar(255));
INSERT INTO temp
SELECT startdate,stuff
FROM mytable;
TRUNCATE TABLE mytable;
ALTER TABLE mytable ALTER COLUMN startdate DATETIME NOT NULL;
INSERT INTO mytable
SELECT CAST(startdate AS DATETIME), stuff FROM temp;
DROP TABLE temp;
First, create the new column with type data
Next, run update query, to populate the new column with the value of the old one, applying any conversion if needed
Next, drop the old column
Finally, rename the new column to the old one
Create a new DATE column with a temporary name
Populate the new column with an UPDATE query that makes use of STR_TO_DATE()
If everything's right, remove the VARCHAR column and rename the DATE column.
Mysql default date format is : YYYY-MM-DD . If your try to insert the date otherwise, as you actually did, the date will be inserted with these values : 000-00-00, giving you a hint to the acceptable date format for mySql.
Wanna share this for SQL server users. For me this method is much convenient and safer.
In your Table create new column "NewDate" (temporarily or name whatever you want).
Make sure no invalid Datetime format in the Table you want to convert. Try those formats here: https://www.w3schools.com/sql/trysqlserver.asp?filename=trysql_func_sqlserver_cast3 <--- you need to check thoroughly otherwise there would be an error executing the command below.
Execute this command:
UPDATE myTable
SET NewDate = CAST(OldDate AS datetime)
WHERE (OldDate <> '') AND (OldDate IS NOT NULL) --to make sure you cast only what is needed otherwise there would be an error.
You can now delete the old column i.e. "OldDate".
Finally you can drag and drop the new table you've created to the slot where you just deleted the old column in the table design.
If the field of your column is VARCHAR and stored date as DD-MM-YYYY then we have to convert the date in YYYY-MM-DD format by following PHP code.
$cd = array();
$cd1 = array();
$cdf = array();
$getdata = mysqli_query($link,"SELECT columnname FROM tablename");
while($row=mysqli_fetch_array($getdata))
{
$cd = $row['columnname'];
$cd1 = strtotime($cd);
$cdf = date('Y-m-d',$cd1);
mysqli_query($link,"UPDATE tablename SET columnname =
REPLACE(columnname,'$cd','$cdf')");
}
After running this PHP code, in your MySQL table change the datatype of your column to 'DATE'.
It works for me without losing or truncate data.