MySQL search & replace at the beginning/end of a string - mysql

I'm currently developing a search & replace function for my application and I want it to be able to replace a specified string at the beginning/end of a string.
For example:
string = "DadaLalaDada"
gets
string = "DuduLalaDada"
when a search & replace at the beginning of the string with
search = "Dada"
replace = "Dudu"
is performed.
How can I do this in MySQL? I use REPLACE to hit every occurrence in a string, but how to perform this only at the beginning/end?

If you're willing to have the relevant values appear multiple times in your query, this seems to work:
select tab.val,
concat(replace(substring(tab.val, 1, char_length('Dada')), 'Dada', 'Dudu'),
substring(tab.val, char_length('Dada') + 1)) as replace_beginning,
concat(substring(tab.val, 1, char_length(tab.val) - char_length('Dada')),
replace(substring(tab.val, -char_length('Dada')), 'Dada', 'Dudu')) as replace_end
from ( select "DadaLalaDada" as val union select "BlahDadaBlah" ) as tab
Results:
+--------------+-------------------+--------------+
| val | replace_beginning | replace_end |
+--------------+-------------------+--------------+
| DadaLalaDada | DuduLalaDada | DadaLalaDudu |
| BlahDadaBlah | BlahDadaBlah | BlahDadaBlah |
+--------------+-------------------+--------------+

Related

How to concat two rows into string from a result set in MySql?

Basicly this is my mysql query:
select distinct(shipment_tag) from ir_shipment_registry where shipment_id = '2020111'
and the result set:
| shipment_tag |
+--------------+
| Truck |
| Equipment |
| |
How can I concat the two result set into string so that i can assign it to a variable? I tried
SET #purchasetype = (select distinct(shipment_tag) from ir_shipment_registry where shipment_id = '2020111')
but it returns and error says: Subquery returns more than 1 row.
I want something in my variable like : #purchasetype = "Truck, Equipment".
Perhaps use GROUP_CONCAT here:
SET #purchasetype = (SELECT GROUP_CONCAT(shipment_tag SEPARATOR ', ') FROM ir_shipment_registry WHERE shipment_id = '2020111');

MYSQL select function from field value?

I have a table and its data are mentioned below :
id | function
1 | current_date
2 | UUID()
3 | RAND()
Structure of the table is
id int, function varchar(50)
Query : select * from func_table;
My excepted result is
id | function
1 | 2020-08-24
2 | 70d6cffc-ae01-11ea-80ca-c11529136ae3630
3 | 0.982584554752
Thanks in advance.
You can use a giant case expression:
select (case when function = 'current_date' then cast(current_date as char)
when function = 'uuid()' then cast(uuid as char)
when function = 'rand()' then cast(rand as char)
end) as value
If you actually want to evaluate the function directly, then you probably have a problem with your data model. SQL does not directly support such functionality.

How do you add a new object to an existing JSON object in MariaDB?

I have a JSON field with an object in it that contains multiple sub objects. The table looks like this:
+---------+----------------------------------------------------------------+
|store_num| fruit_stock |
+---------+----------------------------------------------------------------+
| AL258 | '{"fruits":{"apple":67,"banana":91,"plum":53}}' |
+---------+----------------------------------------------------------------+
| OR419 | '{"fruits":{"apple":109,"banana":44,"plum":98}}' |
+---------+----------------------------------------------------------------+
I want to add an object {"mango":45} to the "AL258" store using prepared statement. I came accross some issues doing this. First was adding an object to another object was not as straight forward as I thought it would be. It turns out I had to create the mango object using the JSON_OBJECT() funtion to start with so:
JSON_OBJECT("mango", 45)
'{"mango":45}'
I then had to get the contents of the "fruits" object so I had to use the JSON_QUERY() function for that:
JSON_QUERY(fruit_stock, '$.fruits')
'{"apple":67, "banana":91, "plum":53}'
Then had to merge the new mango object and the contents of the fruits object. Since I want to replace the field I'm inserting if it already exists I needed to use the JSON_MERGE_PATCH() function:
JSON_MERGE_PATCH(
JSON_QUERY(fruit_stock, '$.fruits'), -- the contents of fruit_stock: '{"apple":67,"banana":91,"plum":53}'
JSON_OBJECT("mango", 45) -- the new mango object: '{"mango":45}'
)
Now that I have the naked object fields '{"apple":67, "banana":91, "plum":53}', and '{"mango":45}' I needed to combine them into the "fruits" object. To do this I needed to create an entirely new "fruits" object using the JSON_OBJECT() function:
JSON_OBJECT(
'fruits', -- the new fruits object
JSON_MERGE_PATCH( -- the contents of fruit_stock
JSON_QUERY(fruit_stock, '$.fruits'), -- the new mango object
JSON_OBJECT("mango", 45)
)
)
'{"fruits":{"apple":67, "banana":91, "plum":53, "mango":45}}'
Adding in a WHERE clause to select the store...
UPDATE store_table SET fruit_stock =
JSON_OBJECT(
'fruits',
JSON_MERGE_PATCH(
JSON_QUERY(fruit_stock, '$.fruits'),
JSON_OBJECT("mango", 45)
)
)
WHERE HEX(store) = 'AL258';
Results in the following table:
+---------+----------------------------------------------------------------+
|store_num| fruit_stock |
+---------+----------------------------------------------------------------+
| AL258 | '{"fruits":{"apple":67,"banana":91,"plum":53,"mango":45}}' |
+---------+----------------------------------------------------------------+
| OR419 | '{"fruits":{"apple":109,"banana":44,"plum":98}}' |
+---------+----------------------------------------------------------------+
My question: Is this the best way to do this, or is there a more efficient and/or readable option using MariaDB?
Just use the similar syntax as the existing jsons for the values to be added by using JSON_MERGE_PATCH() function :
UPDATE store_table
SET fruit_stock = JSON_MERGE_PATCH(fruit_stock, '{"fruits":{"mango": 45}}')
WHERE store_num = 'AL258';
Demo

function to check a text field

im using access 2007 and i need a function that will check a text field and if it found a certain word it will return a certain value according to lookup table
for example i have a text field as following :
ID Text
| 1 | engineers for mechanical work
| 2 | engineers for civil work
| 3 | engineers for electrical work
and i have lookup table as following :
Checkwords showords
| mechanical | mechanical engineer
| civil | civil engineer
| chemical | chemical engineer
| electrical | electrical engineer
| maintenance | maintenance engineer
| electronics | electronics engineer
i need the function to check the text records and if it found text like "mechanical" it will show "mechanical engineer" and if it found text like "civil" it will show "civil engineer" and so on
i have about 200 words to check so i need a function that uses a lookup table with "like" parameter ... is that possible ???
OK then, a more generic version, though be warned - the more you lean on VBA rather than SQL, the slower things get with large and even not-so-large amounts of data:
(1) Add a class module, name it LookupData, and add the following fields to it:
Public Key As String
Public Value As String
(2) In a standard module, define the following function:
Function LookupShowWords(ByVal Text)
If IsNull(Text) Then
LookupShowWords = Null
Exit Function
End If
Dim Data As LookupData
Static LookupTable As VBA.Collection
If LookupTable Is Nothing Then
Set LookupTable = New VBA.Collection
Dim RS As DAO.Recordset
Set RS = CurrentDb.OpenRecordset("LookupTable", dbOpenForwardOnly)
While Not RS.EOF
Set Data = New LookupData
Data.Key = "*" + RS(0) + "*"
Data.Value = RS(1)
LookupTable.Add Data
RS.MoveNext
Wend
End If
Dim S As String
For Each Data In LookupTable
If Text Like Data.Key Then
If Len(S) = 0 Then
S = Data.Value
Else
S = S + ";" + Data.Value
End If
End If
Next
If Len(S) = 0 Then LookupShowWords = Null Else LookupShowWords = S
End Function
(3) The query to list the results can now be rewritten to look simply like this:
SELECT ID, LookupShowWords(Text) AS ShowWords FROM MainTable ORDER BY ID;
Note that the assumption in (2) is that the lookup table is essentially static, in which case its contents can be safely cached between calls.
(1) A custom VBA function to extract the key word:
Function ExtractKeyword(ByVal Text)
Text = Mid(Text, InStr(Text, " for ") + 5)
If Right(Text, 5) = " work" Then
ExtractKeyword = Left(Text, Len(Text) - 5)
Else
ExtractKeyword = Text
End If
End Function
(2) A query to use it:
SELECT MainTable.ID, LookupTable.ShowWords
FROM MainTable LEFT JOIN
LookupTable ON ExtractKeyword(MainTable.Text) = LookupTable.CheckWords
ORDER BY MainTable.ID

SQL query to remove certain text from each field in a specific column?

I recently recoded one of my sites, and the database structure is a little bit different.
I'm trying to convert the following:
*----*----------------------------*
| id | file_name |
*----*----------------------------*
| 1 | 1288044935741310953434.jpg |
*----*----------------------------*
| 2 | 1288044935741310352357.rar |
*----*----------------------------*
Into the following:
*----*----------------------------*
| id | file_name |
*----*----------------------------*
| 1 | 1288044935741310953434 |
*----*----------------------------*
| 2 | 1288044935741310352357 |
*----*----------------------------*
I know that I could do a foreach loop with PHP, and explode the file extension off the end, and update each row that way, but that seems like way too many queries for the task.
Is there any SQL query that I could run that would allow me to remove the file exentision from each field in the file_name column?
You can use the REPLACE() function in native MySQL to do a simple string replacement.
UPDATE tbl SET file_name = REPLACE(file_name, '.jpg', '');
UPDATE tbl SET file_name = REPLACE(file_name, '.rar', '');
This should work:
UPDATE MyTable
SET file_name = SUBSTRING(file_name,1, CHAR_LENGTH(file_name)-4)
This will strip off the final extension, if any, from file_name each time it is run. It is agnostic with respect to extension (so you can have ".foo" some day) and won't harm extensionless records.
UPDATE tbl
SET file_name = TRIM(TRAILING CONCAT('.', SUBSTRING_INDEX(file_name, '.', -1) FROM file_name);
You can use SUBSTRING_INDEX function
SUBSTRING_INDEX(str,delim,count)
Where str is the string, delim is the delimiter (from which you want a substring to the left or right of), and count specifies which delimiter (in the event there are multiple occurrences of the delimiter in the string)
Example:
UPDATE table SET file_name = SUBSTRING_INDEX(file_name , '.' , 1);