简体   繁体   中英

Can't concat values with GROUP_CONCAT on joins

Could anybody help me?

With this query I am getting the ids, but it is not putting the separators when subscriber_data.fieldid is null. For example instead of coming 2,,12 it comes 2,12 when the value for 4 is null...

I think the problem is on the Join with subquery, but i couldn't make it with two left joins in the main query also...

This is the query im using:

SELECT 
    list_subscribers.emailaddress, 
    (SELECT 
         GROUP_CONCAT(IFNULL(customfields.fieldid,'') SEPARATOR '","') 
     FROM customfields 
     LEFT JOIN subscribers_data 
         ON subscribers_data.fieldid = customfields.fieldid 
     WHERE 
         customfields.fieldid IN (2,4,12,13,14,15,17,19,20,21,22,23,16,26,27) 
             AND 
         list_subscribers.subscriberid = subscribers_data.subscriberid
    ) AS data FROM list_subscribers

Thanks everyone.

The left join is useless. Because you have a condition on subscriber_data in the WHERE clause, that subquery will not return those rows for which there is no matching subscriber_data, so it effectively works as if you used INNER JOIN. You should add that condition to the left join condition, but it is impossible in this query layout. Values from the outer query are not allowed in join conditions in the inner query.

You could change it, but apparently you need to join three tables, where the middle table, subscriber_data, that links them all together, is optional. That doesn't really make sense.

Or maybe customfields is the table that is optional, but in that case, you should have reversed the table or used a RIGHT JOIN.

In conclusion, I think you meant to write this:

select
  s.emailaddress,
  GROUPCONCAT(IFNULL(f.fieldid, '') SEPARATOR '","')
from
  list_subscribers s
  inner join subscribers_data d on d.subscriberid = s.subscriberid
  left join customfields f on f.fieldid = d.fieldid
where
  d.fieldid in (2,4,12,13,14,15,17,19,20,21,22,23,16,26,27)
group by
  s.emailaddress

Or do you want to list the id's of the fields that are filled for the subscriber(s)? In that case, it would be:

select
  s.emailaddress,
  GROUPCONCAT(IFNULL(d.fieldid, '') SEPARATOR '","')
from
  list_subscribers s
  cross join customfields f
  left join subscribers_data d on 
    d.subscriberid = s.subscriberid and
    d.fieldid = f.fieldid
where
  f.fieldid in (2,4,12,13,14,15,17,19,20,21,22,23,16,26,27)
group by
  s.emailaddress

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM