Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql IF IN GROUP_CONCAT breaks

Im doing a fairly big SQL so I apologizes that cant provide a bigger example of my tables.

SELECT 
customer_id,
agreement_id,
if( 'network' IN ( GROUP_CONCAT( DISTINCT services.service_code
                                 SEPARATOR ',' )  ),
                  'Yes','No') as networkservice
FROM customers
INNER JOIN agreement USING(customer_id)
INNER JOIN services USING(agreement_id)
GROUP BY customer_id

A customer can have a agreement and a agreement can have a lot of services. What I'm trying to find out is if 'network' is one of the services in that agreement.

Since GROUP_CONCAT returns a comma separated list it feels perfect for my case. But I cant get it to work and I'm running out of ideas.

If there's only one service and that service is 'network' it returns yes, but if there's more then one it returns No.

If I use (INT)service_id instead it makes no difference, unless the INT Im looking for is first in the list. But thats only for INT, if 'network' is first in the list it returns No.

I've tried:

if( 'network' IN ( CAST(GROUP_CONCAT( DISTINCT services.service_code
                                      SEPARATOR ' ' ) AS CHAR)  ),
                   'Yes','No')

And

if( 'network' IN ( concat('\'',
                   GROUP_CONCAT(DISTINCT services.service_code
                                SEPARATOR '\', \'' ),
                   '\'') ), 'Yes','No')

I can provide more examples if my explanation sound confusing.

Thanks.

like image 605
Cleric Avatar asked Aug 31 '11 15:08

Cleric


People also ask

What does Group_concat do in MySQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.

Is there a length limit to Group_concat?

I'm using GROUP_CONCAT() in a MySQL query to convert multiple rows into a single string. However, the maximum length of the result of this function is 1024 characters.

What is the difference between concat and Group_concat in MySQL?

The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.

Can we use Group_concat in SQL Server?

GROUP_CONCAT is a function which concatenates/merges the data from multiple rows into one field. It is a GROUP BY function which returns a string if the group contains at least 1 non-null value, if it does not, it returns a Null value.


1 Answers

I'm a big fan of group_concat, but you don't require group_concat in this case

sum( if(services.service_code='network', 1, 0) ) as networkservice
like image 106
ajreal Avatar answered Oct 09 '22 00:10

ajreal