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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With