count of comma separated values in column mysql - mysql

SELECT ifnull(LENGTH(GROUP_CONCAT(varchar SEPARATOR ',')) - LENGTH(REPLACE(GROUP_CONCAT(varchar SEPARATOR ','), ',', '')) + 1,0) AS total
FROM tablename
WHERE date(date and time)=curdate()
varchar this column contain comma separated values with this I am getting count of comma separated values in column exactly but not working for large data.
is there any solution to get count without length problem

You may be hitting limit of group_concat_max_len - that means that anything longer than (by default) 1024 chars will be truncated so you don't get all results.
Possible solution is counting items per row and summing rows counts.
SELECT SUM(ifnull(LENGTH(varchar) - LENGTH(REPLACE(varchar, ',', '')) + 1,0)) AS total
FROM tablename
WHERE date(date and time)=curdate()
That way you don't need to think about that limit at all.
Just raising group_concat_max_len is not really a viable solution because you will only hit it later.
The real solution is to get rid of comma separated lists and introduce another table where each item will be separate row. That way most counts and similar operations are simpler.

Related

SELECT/LOCATE Query Outputting Incorrect Results

I have a column (kills) with values separated by colons as such: 0;2;0. I wanted to select whatever the middle digit may be, and came up with this query:
SELECT RIGHT(kills, LOCATE(';', kills) - 1)-LEFT(kills, LOCATE(';', kills) - 1) FROM stats WHERE id='135' AND LOCATE(';', kills) > 0;
(I'm aware the where clause is specific, it was for debug purposes. It would realistically be set to a variable which outputs the row id)
It works perfectly fine when the results all have the same decimal place such as 1;2;3 or 10;20;30, but returns wild results when the case is otherwise, such as 1;20;30 or 10;20;3.
1;20;21 outputs 0. -- 10;20;2 outputs -10.
2;20;21 outputs -1. -- 20;20;2 outputs -20.
9;20;21 outputs -8. -- 90;20;2 outputs -90.
I would like to select the middle value of all of these values even if one value doesn't share the same decimal place.
If you want the middle number of three, then you want the second number. Use substring_index():
select substring_index(substring_index(kills, ';', 2), ';', -1)

Mysql: search for a substring and return the one with the highest # to the right of it

I need to search a string in a mysql field for a substring and return the number to the right of it, if it is the highest number of all the rows returned. (The word will most likely occur many times in the string.)
SELECT max(cast(substring(mq.my_query_string, (locate("near/", mq.my_query_string)+5), 2) as signed)) AS "MaxNearDistance"
FROM my_query mq, my_test mt
WHERE mt.company_id = 123
AND mq.search_query_id = mt.my_query_id
AND locate("near/", mq.my_query_string) > 0;
This works, but it only gives me the highest number of the FIRST substring and among all rows returned. I need the highest number among ALL hits for the substring and among all rows.
Thank you for your help!
I would create a table- numbers- with every number string I want to be able to find ('0' - '99' for you) then join it to my data like:
SELECT
mq.my_query_string, MAX(numbers.ns)
FROM my_query AS mq
JOIN numbers ON CONCAT(mq.my_query_string, ' ') LIKE CONCAT('%near ', numbers.ns, ' %')
GROUP BY mq.my_query_string
I'm CONCATing a space to the data so that '11' won't match '1'.
SQLFiddle here: http://sqlfiddle.com/#!2/8fda1c/4
(Actually, the right way is to normalize your data so you have a table of my_query_nears with one value per row but sometimes we must play the hand we are dealt.)

Using distinct and order by in subquery

I am trying to get distinct 'productnumber' ordered by the 'createdate' but at the end I need only "productnumber" sorted by 'createdate' (I cannot use top as the 'productnumber' varies in a wide flexible range).
The distinct product number is needed to be concatenated with comma (,) for e.g.
123,245,787,875 (each number represents a productnumber)
The required query looks like somewhat (this query doesn't work and gives an error The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified):
SELECT stuff(
(
SELECT distinct ',' + productnumber
FROM Product
ORDER BY createdate
FOR XML path('')
)), 1, 1, '')
Could anyone help in how to go about to get the desired result.
As Mikael Eriksson suggested, using Group By clause solved the problem. Thanks Mikael
SELECT stuff((SELECT ',' + productnumber
FROM product a
ORDER BY a.createdate FOR xml path('')),1,1,'')
AS destn_str

query to remove all characters after last comma in string

i have a mysql table with this sort of data
TACOMA, Washington, 98477
Now i have thousands of such rows. I want the data to be manipulated in such a manner that it appears like:
TACOMA, Washington
Is it possible though mysql or do i have to manually do it.
You can use :
SELECT SUBSTRING_INDEX('TACOMA, Washington, 98477', ',', 2)
You can read more here.
And the update statement :
UPDATE my_table
SET my_col = SUBSTRING_INDEX(my_col, ',', 2)
Where you need to replace my_table with your table name and my_col with the column you need to be updated.
Possibly this way. Count the number of commas (by checking the length against the length with all the commas removed) and then use SUBSTRING_INDEX to get the string up to the number of commas:-
SELECT SUBSTRING_INDEX(col, ',', LENGTH(col) - LENGTH(REPLACE(col, ',', '')))
FROM SomeTable
substring_index(col, ',',-1)
will give the string from last index of comma to end of string
replace(col,concat(',',substring_index(col, ',',-1)),'')

Sort by the number of words in a MySQL field

I would like to sort a result from a MySQL query by the number of words in a specified column.
Something like this:
SELECT bar FROM foo ORDER BY WordCountFunction(bar)
Is it possible?
As far as I know, there is no word count function in MySQL, but you can count the number of spaces and add one if your data is formatted properly (space separator for words, no spaces at beginning/end of entry).
Here is the query listing longest words first:
SELECT bar FROM foo ORDER BY (LENGTH(bar) - LENGTH(REPLACE(bar, ' ', ''))+1) DESC
Using this method to count the number of words in a column, your query would look like this:
SELECT bar FROM foo ORDER BY (LENGTH(bar) - LENGTH(REPLACE(bar, ' ', ''))+1) DESC
Yes, sort of. It won't be 100% accurate though:
SELECT SUM(LENGTH(bar) - LENGTH(REPLACE(bar, ' ', ''))+1) as count
FROM table
ORDER BY count DESC
But this assumes the words are separated by a space ' ' and doesn't account for punctuation. You can always replace it with another char and it doesn't account for double spaces or other chars either.
For complete accuracy, you could always pull the result out and word-count in your language of choice - where accurate word-count function do exist!
Hope this helps.