Thursday, January 29, 2015

mysql select field as json text using concat, group_concat, distinct

select a.id, a.title, a.subtitle, a.createddate, a.user_id,
u.username, u.displayname, u.thumburl,
CONCAT(
    '[',
    GROUP_CONCAT(DISTINCT(
            
        CONCAT(
            CONCAT('{"id":"',m.id,'"'),
            CONCAT(', "typecode":"',m.typecode,'"'),
            CONCAT(', "thumburl":"',ifnull(m.thumburl,''),'"}')
        )
       
    ) ORDER BY m.typecode, am.ordering ASC SEPARATOR ',' ),
    ']'
) as medias
from (
    select id, title, subtitle, createddate, user_id from article
    where user_id in (select user_id from follow where follow_user_id = 33 OR user_id = 33)
    ) as a
left join article_media as am on a.id = am.article_id
left join media as m on am.media_id = m.id
left join (
    select u.id, u.username, u.displayname, u.picture_id, m.thumburl
    from (
        select id, username, displayname, picture_id from user
        where id in (select user_id from follow where follow_user_id = 33 OR user_id = 33)
    ) as u
    left join media as m on u.picture_id = m.id
) as u on a.user_id = u.id
where u.username != 'root'
group by a.id

No comments: