I want to create records of tier 2 with using the name of tier 1 records and appending 2 in their name. Like "Tools 2", I want to create records for other records (with tier = 1).
I am using this query in mysql -
insert into dummy_1 (ca2_name, ca2_tier) VALUES (CONCAT(select ca2_name from dummy_1 where ca2_tier=1, " 2"), 2);
But it is throwing error - "CONCAT" is not valid at this position, expecting a complete function. Not sure how to implement this.
When you use a subquery as an expression, it has to be enclosed in parentheses, in addition to the parentheses that are used for wrapping the CONCAT arguments.
insert into dummy_1 (ca2_name, ca2_tier)
VALUES (CONCAT((select ca2_name from dummy_1 where ca2_tier=1), " 2"), 2)
But a better way to write this is to use a SELECT instead of VALUES.
INSERT INTO dummy_1 (ca2_name, ca2_tier)
SELECT CONCAT(ca2_name, ' 2'), 2
FROM dummy_1
WHERE ca2_tier = 1
Related
DISCLAIMER: NONE OF THESE VALUES ARE TRUE/REAL, ITS JUST A PRACTICE ASSIGNMENT
how to randomize the last 6 digits of the DBS account and obscuring the first 4 digits of the NRIC number with x using mysql. All values were keyed in manually and do not relate to each other.
Current
Desired Result
Just use substring operations:
SELECT
CONCAT('XXXX', SUBSTRING(NRIC, 5, 4)) AS NRIC,
Name,
Contact,
Salary,
CONCAT(SUBSTRING(DBS_Account, 1, 3), '-XXXXX-X') AS DBS_Account
FROM yourTable;
mysql rand function - https://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_round
using substring and concat
SELECT CONCAT(SUBSTRING(RAND(),3,5),'-',SUBSTRING(RAND(),3,1))
will give something like 40033-8
then concat with substring
set #a ='038-12645-6';
SELECT CONCAT(substring_index(#a,'-',1),'-',SUBSTRING(RAND(),3,5),'-',SUBSTRING(RAND(),3,1));
'038-63475-5'
i would like to perform Mysql search & replace with random characters, taken from a list. I cannot use regex, since my version is way prior to 8.
instead of the below,
i would like to change for instance the letter u with one out of (a,e,i,f,k) randomly.
UPDATE products
SET
productDescription = REPLACE(productDescription,
'abuot',
'about');
Is there a mysql command for this task?
Actually my goal is to get in the lastnames column, new names that are not exactly like the real ones, so one could work on "anonymous" data.
I would like to replace all rows in a certain column. Say in table products, in column description, we have data like:
abcud
ieruie
kjuklkllu
uiervfd
With the replace function, we would not want to create something like: replace e with i,
but replace e with one of (a,e,i,f,k)
example desired output:
abced
ierfie
kjiklkllk
aiervfd
like i said, we plan to use this into last names, we plan to replace many characters with random ones from a list, in an effort to create anonymous data in the column that contains last names.
On a next step, i would like to do the same, in order to make anonymous telephone numbers.
example
726456273
827364878
347823472
replace 3 with one of 0-9,
output:
726456279
827664878
547821472
SELECT REPLACE('product abuot Description',
SUBSTRING('product abuot Description', CHARINDEX('abuot', 'product abuot Description') ,5) , 'about')
CREATE FUNCTION smart_replace ( argument TEXT,
search_for CHAR(1),
replace_with TEXT )
RETURNS TEXT
NO SQL
BEGIN
SET argument = REPLACE(argument, search_for, CHAR(0));
REPEAT
SET argument = CONCAT( SUBSTRING_INDEX(argument, CHAR(0), 1),
SUBSTRING(replace_with FROM CEIL(RAND() * LENGTH(replace_with)) FOR 1),
SUBSTRING(argument FROM 2 + LENGTH(SUBSTRING_INDEX(argument, CHAR(0), 1))));
UNTIL NOT LOCATE(CHAR(0), argument) END REPEAT;
RETURN argument;
END
replace e with one of (a,e,i,f,k)
SELECT smart_replace(table.column, 'e', 'aeifk')
replace 3 with one of 0-9
SELECT smart_replace(table.phone, 'e', '0123456789')
I have the following imported to TableA, Column 'Clothes' and Column 'Colours'
The problem is the import has put in the 'Clothes' column 'Jeans - Blue' and 'Jumper - Red' etc etc
Please could someone help me with a query to keep everything before the - in 'Clothes' and everything after the - into 'Colours' and removing the - altogether.
Two steps for this.
First, update the colors:
UPDATE yourTableA T
SET T.Colours = TRIM(SUBSTR(T.Clothes,INSTR(T.Clothes,'-') + 2));
Second, update the Clothes:
UPDATE yourTableA T
SET T.Clothes = TRIM(SUBSTR(T.Clothes,1,INSTR(T.clothes,'-')-1));
I've used SUBSTR as my string swiss army knife here, and INSTR to locate the position of the - in between. You can do without TRIM, but I usually use this in those cases to avoid unnecessary white spaces.
There surely are more direct ways to do it, but this'll work.
The SUBSTRING_INDEX function is convenient, and the TRIM function can remove leading and trailing spaces. For example:
SELECT TRIM(SUBSTRING_INDEX(a.Clothes,'-',1)) AS Clothes
, TRIM(SUBSTRING_INDEX(a.Clothes,'-',-1)) AS Colours
FROM TableA a
WHERE LENGTH(a.Clothes)-LENGTH(REPLACE(a.Clothes,'-','')) = 1
(NOTE: the query above is returning the substring before the first '-' character, and is returning the substring after the last '-' character. So any values with more than one dash would lose the portion between the first and last dashes, consider e.g. 'A - B - C - D', the query above returns the A and returns the D, and loses everything else.
To handle this anomaly, the WHERE clause checks that the string contains a single occurrence of the '-' character.
Once you have a query you are happy with, you can turn that into an UPDATE statement, BUT be VERY careful about the order you assign new values to columns. Unlike other relational databases, MySQL does not guarantee that a reference to an existing column within the statement will be the value of the column from the beginning of the statement... the only guarantee is that it will be the value that is currently assigned. So, the order that the columns is assigned is important!
UPDATE TableA a
SET Colours = TRIM(SUBSTRING_INDEX(a.Clothes,'-',-1))
, Clothes = TRIM(SUBSTRING_INDEX(a.Clothes,'-',1))
WHERE LENGTH(a.Clothes)-LENGTH(REPLACE(a.Clothes,'-','')) = 1
Note that if we were to assign the Clothes column before we assigned a value to the Colours column, the value we want assigned to Colours would be "lost".
You can do it in a single UPDATE as follows:
UPDATE TableA
SET `Colours` = SUBSTRING_INDEX(`Clothes`, ' - ', -1),
`Clothes` = SUBSTRING_INDEX(`Clothes`, ' - ', 1)
;
You can experiment with SQL Fiddle Demo I created from your data.
Here's the data I worked with:
CREATE TABLE TableA
(Clothes varchar(20), Colours varchar(20))
;
INSERT INTO TableA
(`Clothes`, `Colours`)
VALUES
('Jeans - Blue', NULL),
('Jumper - Red', NULL)
;
This the result of SELECT * FROM TableA; :
CLOTHES COLOURS
Jeans Blue
Jumper Red
I'm inserting into my database here with parameters from the form.
The form has 4 input fields (current_no, current_street, current_city, current_state). I've set it up so that the client can display each of these values on the web page, but what they want is to be able to view these values in a single column.
so basically from...
current_no | current_street | current_city | current_state
to...
| current_no current_street current_city current_state |
I decided I'd add another column to the table that'll store this "full" value and I figured that populating it would probably be easy but I think I'm missing something here:
insert into customers(current_address) values (current_no + ' ' + current_street + ' ' + current_city + ' ' + current_state)
Although this doesn't give me any errors, it only inserts the current_no value into the column.
How can I concatenate all the values (string types) into the column on database side?
Thanks in advance for any help!
in mySQL use CONCAT()
insert into customers(current_address) values
(
(CONCAT(current_no,' ',current_street,' ',current_city,' ',current_state)
)
or CONCAT_WS()
insert into customers(current_address) values
(
(CONCAT_WS(' ', current_no,current_street,current_city,current_state)
)
Try using
INSERT INTO customers (current_address)
SELECT
CONCAT_WS(' ', current_no, current_street, current_city, current_state)
Others have suggested CONCAT_WS and that's right. The + operator the SQL language doesn't concatenate strings, as you have discovered.
But, please think about your plan of adding a new column to your table for this. New columns with redundant data aren't usually a great idea.
If you already have the columns with the data in them, I suggest you use a SELECT query when you read the table to create your concatenated column. This will take advantage of the data you already have without placing redundant data in the table.
SELECT CONCAT_WS(' ', current_no,current_street,current_city,current_state)
AS current_address
My table column has rows like this 1001, 1002, 1003 and so on separated by commas. There may be 1 or more comma separated values in each column. I need the total count of these comma separated values in the table. For example if my table has 2 rows one having 1001, 1002, 1003, 1004 and another with 1001, 1005 the output i should get is 6 i.e. 4+2. Kindly assist
there is no function in mysql to count char occurences. but you can replace every comma with nothing. and then you calculate the difference of lenghts which will give you the number of commas, which is one less than the number of values.
select
( LENGTH(col1) - LENGTH(REPLACE(col1, ',', '')) + 1 )
+ ( LENGTH(col2) - LENGTH(REPLACE(col2, ',', '')) + 1 )
AS valCount
from T;
(didn't test that explicitely but at least something very similar to that will do the job.)
replace()
length()
Try:
SELECT SUM(LEN(ColumnName) - LEN(REPLACE(ColumnName, ',', ''))) FROM TableName
This is one of those tasks that'd be much, much easier in the server-side script accessing your database than the database itself. Assuming you've already assigned the comma-separated strings to an array (where $array[1] is equal to the string from row 1:
$array = array("1001, 1002, 1003, 1004", "1001, 1005"); // assigned from database
foreach($array as $k => $v){
$numbersInString[$k] = count(explode(', ', $v));
}
echo implode(' + ',$numbersInString);
This is possible, with creative solutions (such as that from Raffael1984), in MySQL, but seems to much more easily, and concisely, implemented in PHP.
References:
count().
explode().
implode().
foreach().
Did you try using the count() function? You can specify which rows if you need to.
.row[COUNT(name)]
in your query. What does your table look like? I might be able to help more if I know what it looks like