MySQL group_concat and concat - mysql

I have these data on MySQL table cart.
I would like to run a query that would output like this:
Advance Technique Conditioner (2), Advance Technique Gel (1)
So I was doing a group_concat query and was trying queries to output my desired output. This is the query that outputted the nearest to the desired:
select concat(group_concat(product separator ', '), group_concat(quantity separator ', ')) as 'prod' from cart where debt_no='0000001'
But as expected, it outputted like this : Advance Technique Conditioner, Advance Technique Gel2, 1
How can I get the desired output?

CONCAT() should be inside GROUP_CONCAT()
GROUP_CONCAT(CONCAT(product, ' (', CAST(quantity AS CHAR(15)), ')') SEPARATOR ', ')
remember that the default length of GROUP_CONCAT() is 1024. So if you want to change the limit execute the following line,
SET [GLOBAL | SESSION] group_concat_max_len = val; -- val is the new length

SELECT GROUP_CONCAT(CONCAT(product, ' (', quantity, ')') SEPARATOR ', ')

You need to do the concat() first, then the group_concat():
select group_concat(concat(product, ' (', quantity, ')') separator ', ') as prod
from cart where debt_no='0000001'

Related

How to execute MYSQL REPLACE to replace multiple or single space with | (pipe)

SELECT * FROM `spamfilter` WHERE `words` REGEXP (REPLACE('test won hello spam', " ", "|"))
works for one space.
SELECT * FROM `spamfilter` WHERE `words` REGEXP (REPLACE('test[2 spaces]won[2 spaces]hello[2 spaces]spam', "[2 spaces]", "|"))
works for two spaces.
SELECT * FROM `spamfilter` WHERE `words` REGEXP (REPLACE('test[5 space]won[2 space]hello[1 space]spam', " ", "|"))
won't work for multiple or single spaces in one query.
This works with one space and I need it to work if it has multiple spaces in one query.
I assume that you know the maximum length of multi spacers in the text.
Let's say maximum length is 3: in this case you have to run the query 3 times like this:
// for three spaces
update tableName set colName = REPLACE(LTRIM(RTRIM(colName)), ' ', '|') where colName like '% %'
//for two spaces
update tableName set colName = REPLACE(LTRIM(RTRIM(colName)), ' ', '|') where colName like '% %'
//for one space
update tableName set colName = REPLACE(LTRIM(RTRIM(colName)), ' ', ' ') where colName like '% %'
There may be a better approach, but this one should work too..
I think this handles up to 12 spaces:
REPLACE(
REPLACE(
REPLACE(
REPLACE(TRIM(col), ' ', ' ') --5
' ', ' ') --3
' ', ' ') --2
' ', '|')

Rewriting multiple SQL commands into a single query

I am trying to turn this statement:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when year = ',
year,
' then experience_rate end) AS `',
year, '-Pen`'
) ORDER BY year
) INTO #sql
FROM
spooner_pec;
SET #sql = CONCAT('SELECT policy_number, primary_name, ', #sql, '
FROM spooner_pec
GROUP BY policy_number');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Into something like this:
SELECT policy_number, primary_name, (SELECT GROUP_CONCAT(DISTINCT CONCAT('max(case when year = ', year, ' then experience_rate end) AS `', year, '-Pen`') ORDER BY year))
FROM spooner_pec
GROUP BY policy_number
But as you can see by the fiddle, I am getting some strange output as a column instead of the actual columns, what am I doing wrong here?
SQLFiddle
I generally do regular expression search to get all the code in single line or selected code in single line.
Use find & replace
1. Under find section type "\n" --find all next line keywords
2. Under replace section type " " -- replace \n with one blank space
3. Tick "Use Regular Expression"
Your result will be in single line.
Before
After
Replace with section is a blank space
*Note: This approach works on Windows platform and most of the editors.

MySql replacing spaces with hyphens

A day ago, I asked this question on stackoverflow. Sure, that works well, but does anyone know how I can do the same thing in a MySql statement without any php involved?
Eg: select preg_replace(:songName,' ', '-') //Ugh, this is wrong.
What I'm trying to do Is replace spaces with a -. But sometimes, when there is a space, I'll get more -
Eg: Metallica - Hero of the Day ends up as Metallica---Hero-of-the-Day
Any chance of making it just: Metallica-Hero-of-the-Day
BTW: It's not only song names I'm replacing.
I'm ok with a simple MySql replace, but I can see doing the above is going to need more than that.
I would replace spaces with hyphens first, then deal with any multiple hyphens that may have been created:
select replace(replace(replace(songTitle, ' ', '-'), '---', '-'), '--', '-')
I've replaced --- and -- separately because there are edge cases which overall would require both, and in that order.
See SQLFiddle
Use a user defined function like this(use delimetres accordingly)
CREATE FUNCTION replace_spaceWithHyphen(textToReplace varchar(100))
RETURNS TEXT
BEGIN
DECLARE occHyphen int;
DECLARE occSpace int;
set occHyphen = 1;
set occSpace = 1;
WHILE (occHyphen <> 0 || occSpace <> 0) DO
SELECT LOCATE('--',textToReplace) into occHyphen;
SELECT LOCATE(' ',textToReplace) into occSpace;
SELECT REPLACE(textToReplace,' ','-') into textToReplace;
SELECT REPLACE(textToReplace,'--','-') into textToReplace;
END WHILE;
RETURN textToReplace;
END;
Then call your select like this:
SELECT replace_spaceWithHyphen('Metallica - Hero of the Day');
Answer would be:
TEXT
Metallica-Hero-of-the-Day
SAMPLE FIDDLE
This should work:
select
replace(
replace(
replace('Metallica - Hero of the Day', '-', ' ')
, ' ', '')
, ' ', '-')
You may write your query. It is so easy for you.
Suppose you have a table named class(id, classname) with two fields. Now you insert in your table in classname field i.e. Metallica - Hero of the Day.
Now you can execute this by below given program.
mysql_connect('localhost','root','');
mysql_select_db('dbname'); // Please insert your dbname
$query = mysql_query('SELECT classname, REPLACE(classname," ","-") from class');
$record = mysql_fetch_array($query);
echo $record['REPLACE(classname," ","-")'];
It will give output. i.e. Metallica---Hero-of-the-Day.
and if you replace your query with. I have taken help from Bohemian answer for below query.
$query = mysql_query("SELECT classname, replace(replace(replace(classname, ' ', '-'), '---', '-'), '--', '') from class");
$record = mysql_fetch_array($query);
echo $record["replace(replace(replace(classname, ' ', '-'), '---', '-'), '--', '')"];
You will get result i.e. Metallica-Hero-of-the-Day
That's it. Easy.
Thanks
You can try this method.
UPDATE TABLE_NAME SET column_name = REPLACE(column_name, old_value, new_value);
For Example
UPDATE TABLENAME SET column_name = REPLACE(column_name, '-', ' ');
Hope this will helps you.

How do I fetch rows from a MySQL database with multiple like combinations?

I need to fetch rows from a table having WHERE condition with multiple LIKE combinations,
I mean, for example, I have a field description in the table which has two rows
1. 'abc def hij klm'
2. 'opq rst uvw xyz'
My search text is abc rst. So I need a query with a LIKE condition that must produce both the rows, because the first row contains the string abc and second contains rst. I know I can use the OR in between two LIKE condition, but what should I do if the search text is too long because it has more words?
This can be a bit painful, but one way to do it is with like and substring_index()
where concat(' ', description, ' ') like concat('% ', substring_index(#SearchString, ' ', 1), ' %') and
concat(' ', description, ' ') like concat('% ', substring_index(substring_index(#SearchString, ' ', 2), ' ', -1), ' %') and
concat(' ', description, ' ') like concat('% ', substring_index(substring_index(#SearchString, ' ', 3), ' ', -1), ' %') and
concat(' ', description, ' ') like concat('% ', substring_index(substring_index(#SearchString, ' ', 4), ' ', -1), ' %')
The nested substring_index() return the nth item of the list.
If the codes you are looking for a real codes just glommed together in the description field, then you have bad database design. You need an association table with a single row for each code.
If the description is really a text description, then you might really want full text indexing. This would solve your problem using match . . . against.

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;