Any help would be greatly appreciated.. Im quite new to mySQL and figured there has to be an easier way to update my database.
So my issue is that I have a number of records that don't have a leading zero but I need the total number of characters in any record to be 5.
e.g. 6930 should in fact be 06930
I came across this code but I am unable to get it to work correctly, could anyone point me in the right direction.
UPDATE `it_asset_register`.`tab_id_master`
SET tab_id_master.ID = LEFT('00000', 5-LEN(tab_id_master.ID)) + tab_id_master.ID
WHERE ID = '8407' AND LEN(tab_id_master.ID)<5 AND Len(tab_id_master.ID)>0;
Thanks
LPAD should do the job here:
SELECT LPAD ('123', 5, '0');
00123
SELECT LPAD ('12345', 5, '0');
12345
Try:
UPDATE `it_asset_register`.`tab_id_master`
SET tab_id_master.ID = LPAD (tab_id_master.ID, 5, '0')
WHERE ID = '8407' AND LENGTH(tab_id_master.ID)<5 AND LENGTH(tab_id_master.ID)>0;
To concatenate two or more strings in MySQL, you must use the CONCAT() function.
A possible solution can be:
UPDATE tab_id_master
SET id = SUBSTRING(CONCAT('00000', id), -5)
WHERE LENGTH(id) > 0 AND LENGTH(id) < 5;
Alternatively you can use the LPAD() function:
UPDATE tab_id_master
SET id = LPAD(id, 5, '0')
WHERE LENGTH(id) > 0 AND LENGTH(id) < 5;
Regards
UPDATE
table_name
SET
column_name = RIGHT('00000' + CAST(column_name AS CHAR), 5)
This concatenates the 5 zeros and your ID to something like '000001234'. Then it selects the 5 rightmost characters.
You didn't specify tab_id_master.ID type. If it is of a numeric type you wouldn't be able to store a number with leading zeros but otherwise you could use LPAD():
SET tab_id_master.ID = LPAD(tab_id_master.ID, 5, 0)
Related
I'm trying to get a mysql script, that changes every 4-digit long number "into" a 5-digit long, by adding a "0" at the start of each number. This is, what I tried:
SELECT * FROM `customer_address_entity_text` WHERE CHAR_LENGTH(value) < 5;
SELECT CONCAT("0", CAST(value as CHAR(50)) AS value;
but it shows an error, that there is no field "value" found:
#1054 - Unknown field 'value' in field list (translated)
would be nice, if someone could help me with this.
(it also gives out this error, when I'm not trying to Cast 'value' to a CHAR)
tl;dr: I want 'value = "0" + value' in mysql
example:
'value = 1234; value = "0" + value; value = 01234' and that in mysql
Two issues:
There is a missing closing parenthesis for CONCAT(
Your second SELECT has no FROM clause, so indeed there is no value field there.
So move that CONCAT expression inside the first SELECT clause and balance the parentheses:
SELECT c.*, CONCAT("0", CAST(value as CHAR(50))) AS value
FROM `customer_address_entity_text` c
WHERE CHAR_LENGTH(value) < 5;
If your purpose is to pad all values with zeroes so they get 5 digits, so that it also transforms 1 to "00001" and 12 to "00012", then use LPAD:
SELECT c.*, LPAD(value, 5, "0") AS value
FROM `customer_address_entity_text` c;
To update the value field:
UPDATE `customer_address_entity_text`
SET value = LPAD(value, 5, "0");
Or, with your original concat version:
UPDATE `customer_address_entity_text`
SET value = CONCAT("0", CAST(value as CHAR(50)))
WHERE CHAR_LENGTH(value) < 5;
I have a table with some values like below,
Slno
---------
IFAAA1121
IFAAA1122
IMBBB1121
IMBBB11223
My goal is to reformat the SlNo in to the below format,
Slno
---------
IF-AAA-1121
IF-AAA-1122
IM-BBB-1121
IM-BBB-11223
How is it possible ?
My query is:
UPDATE `certificate_log_uae`
SET `DeviceSerialNumberTemp` = REPLACE(LEFT(DeviceSerialNumberTemp,2),
LEFT(DeviceSerialNumberTemp,2).'-')
You can use the Substr() function to get substrings out from your input string, at various positions and lengths.
Since the length of the last substring is not fixed; we can simply specify the start position to slice the substring, and leave specifying the length parameter. It will consider the substring till the end of the overall string.
Now, just concatenate this substrings back using - appropriately.
Try the following:
UPDATE `certificate_log_uae`
SET `DeviceSerialNumberTemp` = CONCAT(SUBSTR(`DeviceSerialNumberTemp`, 1, 2),
'-',
SUBSTR(`DeviceSerialNumberTemp`, 3, 3),
'-',
SUBSTR(`DeviceSerialNumberTemp`, 6)
)
One approach would be to just build the final string you want using concatenation:
UPDATE certificate_log_uae
SET DeviceSerialNumberTemp = CONCAT(LEFT(DeviceSerialNumberTemp, 2),
'-',
SUBSTRING(DeviceSerialNumberTemp, 3, 3),
'-',
SUBSTRING(DeviceSerialNumberTemp, 6));
Demo
If you are using MySQL 8+ or later, then there is a very simple regex based solution using REGEXP_REPLACE:
SELECT
DeviceSerialNumberTemp,
REGEXP_REPLACE(DeviceSerialNumberTemp, '(.{2})(.{3})(.*)', '$1-$2-$3') AS output
FROM certificate_log_uae;
Demo
Try simple insert function:
select Slno, insert(insert(slno, 3, 0, '-'), 7, 0, '-') from tbl
Demo
To update values try:
update certificate_log_uae set
DeviceSerialNumberTemp = insert(insert(DeviceSerialNumberTemp , 3, 0, '-'), 7, 0, '-')
I have table in that I have one field with dash value. Like...
I need to search this with between condition.
For example if I have one value 25 then I need to search the records which include the value 25 like 20-31. In above image there are 6 records which include 25 value. So it should return 6 records.
Please help me in this query ? What would be the query for that ?
You can use MySQL's substring_index() function to easily get the data before and after the dash:
select substring_index(yourcolumn,'-',1) as `lower`, substring_index(yourcolumn,'-',-1) as `upper`
from yourtable
This way you can return the records where a certain value falls between the range:
select * from yourtable
where 25 between substring_index(yourcolumn,'-',1) + 0 and substring_index(yourcolumn,'-',-1) + 0
The + 0 forces MySQL to convert the result of substring_index() to a numeric value before the comparison.
You can use the following solution using SUBSTRING_INDEX:
SELECT *
FROM table_name
WHERE 25 >= CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 1), '-', -1), UNSIGNED INTEGER)
AND 25 <= CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 2), '-', -1), UNSIGNED INTEGER)
-- or
SELECT *
FROM table_name
WHERE 25 BETWEEN CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 1), '-', -1), UNSIGNED INTEGER)
AND CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 2), '-', -1), UNSIGNED INTEGER)
demo: http://sqlfiddle.com/#!9/4ac7b3/3/0
I recommend you to change your table design. I would split the column using the VARCHAR datatype to two columns using the INTEGER datatype. You can add two new columns with the the following ALTER TABLE commands:
ALTER TABLE table_name ADD colNameA INT;
ALTER TABLE table_name ADD colNameB INT;
To split the values of you current column and update the values to the new columns you can use the following UPDATE command:
UPDATE table_name SET
colNameA = CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 1), '-', -1), UNSIGNED INTEGER),
colNameB = CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 2), '-', -1), UNSIGNED INTEGER)
At the end you can remove the VARCHAR column using this ALTER TABLE command:
ALTER TABLE table_name DROP COLUMN col_name
Now you can use the following (simple) query to get the expected results:
SELECT *
FROM table_name
WHERE 25 >= colNameA AND 25 <= colNameB
-- or
SELECT *
FROM table_name
WHERE 25 BETWEEN colNameA AND colNameB
If you want to get values beween 35 and 39, you can use below query,
SELECT
*
FROM
yourtable
WHERE
35 && 39
BETWEEN SUBSTRING_INDEX(tablecolumn, '-', 1) + 0 AND
SUBSTRING_INDEX(tablecolumn, '-', - 1) + 0
I don't know how it possible with MySQL.
But using php it possible to check with range.
For e.g.
// First of all get all record from database.
$search = 10; // Your searching value.
// Loop all rows.
while($rows = mysqli_fetch_array($r)){
$explode = explode("-",$rows['dash']); // For get from-to value.
$range = isset($explode[0])&&isset($explode[1])?range($explode[0],($explode[1]-1)):array(); // For get range.
if(in_array($search,$range)){ // For check searching value is exist or not !
echo "Yes ! I get into ".$rows['dash']; // Do stuff.
}
}
Note: If 10-15 then it will check with 10,11,12,13,14.
According to me if you dont want to change the table structure then,
Just fetch the records as per your other condition, Then from that data check your amount between that field using foreach loop and explode. like
If you have $data as all data
foreach($data as $value){
$new_val=explode(',',$value['new_field']);
if(25 >= $new_val[0] && 25 <= $new_val[1]){
// here create new array
}
}
I'm trying to search and replace mobile numbers with the full international code.
So where rows have 07970000007 to replace the beginning with +447970000007
UPDATE tblMemberImportClub
SET msisdn = REPLACE(msisdn, '07', '+447')
WHERE INSTR(msisdn, '07') = 1;
But this also replaces the other matches:
+4479700000+447
I don't think i can use TRIM as some rows will already start with +447 and will therefore nor require any updates.
Thanks in advance for any assistance.
Use LIKE and INSERT():
UPDATE tblMemberImportClub
SET msisdn = INSERT(msisdn, 1, 2, '+447')
WHERE msisdn LIKE '07%';
INSERT() is a string function that replaces exactly the characters you specify (see here).
SELECT
CONCAT(
REPLACE(
LEFT('07970000007',2), '07', '+447'
),
SUBSTRING('07970000007', 3, CHAR_LENGTH('07970000007'))
)as replaced
I'm don't have a lot of knowledge of MySql (or SQL in general) so sorry for the noobness.
I'm trying to update a bunch of String entries this way:
Lets say we have this:
commands.firm.pm.Stuff
Well I want to convert that into:
commands.firm.pm.print.Stuff
Meaning, Add the .print after pm, before "Stuff" (where Stuff can be any Alphanumerical String).
How would I do this with a MySql Query? I'm sure REGEXP has to be used, but I'm not sure how to go about it.
Thanks
Try something like this. It finds the last period and inserts your string there:
select insert(s, length(s) - instr(reverse(s), '.') + 1, 0, '.print')
from (
select 'commands.firm.pm.Stuff' as s
) a
To update:
update MyTable
set MyColumn = insert(MyColumn, length(MyColumn) - instr(reverse(MyColumn), '.') + 1, 0, '.print')
where MyColumn like 'commands.firm.pm.%'
Perhaps use a str_replace to replace commands.firm.pm to commands.firm.pm.print
$original_str = "commands.firm.pm.15hhkl15k0fak1";
str_replace("commands.firm.pm", "commands.firm.pm.print", $original_str);
should output: commands.firm.pm.print.15hhkl15k0fak1
then update your table with the new value...How to do it all in one query (get column value and do the update), I do not know. All I can think of is you getting the column value in one query, doing the replacement above, and then updating the column with the new value in a second query.
To update rows that end in '.Stuff' only:
UPDATE TableX
SET Column = CONCAT( LEFT( CHAR_LENGTH(Column) - CHAR_LENGTH('.Stuff') )
, '.print'
, '.Stuff'
)
WHERE Column LIKE '%.Stuff'
To update all rows - by appending .print just before the last dot .:
UPDATE TableX
SET Column = CONCAT( LEFT( CHAR_LENGTH(Column)
- CHAR_LENGTH(SUBSTRING_INDEX(Column, '.', -1))
)
, 'print.'
, SUBSTRING_INDEX(Column, '.', -1)
)
WHERE Column LIKE '%.%'