K'Tyn Fowler

rearrange columns and use aliases

see comments!

  • November 5, 2016 at 7:04 PM
  • Last updated about 9 years ago
  • Visible to public
/* query 1 */

SELECT /* column order is rearranged */
    articles.title, 
    upper(articles.body) as content, /* alias */
    articles.article_id,    
    COUNT(ReplyJoin.comment_id) as replies_count /* alias */
FROM 
    articles
LEFT JOIN /*!! left join is used here because we want to get all articles with or without comments.*/
    comments AS ReplyJoin /* bonus alias */
ON 
    ReplyJoin.article_id = articles.article_id
WHERE 
    (articles.body like '%SWEET%' and articles.user_id < 4) or articles.title like '%blandit%'
GROUP BY 
    articles.article_id
HAVING 
    COUNT(ReplyJoin.comment_id) > 1
ORDER BY 
    articles.title
;

/* query 2 */

SELECT /* column order is rearranged */
    lower(articles.title) as lower_title,  /* alias */ 
    GROUP_CONCAT(comments.body SEPARATOR ' + ') AS comment_summary, /* alias */
    articles.article_id
FROM 
    articles
LEFT JOIN /*!! left join is used here because we want to get all articles with or without comments.*/
    comments
ON 
    comments.article_id = articles.article_id
WHERE
    articles.article_id < 5 and LENGTH(articles.body) > 50 and comments.parent_id is not NULL
GROUP BY 
    articles.article_id
HAVING
    NOT comment_summary like '%bart%'
ORDER BY
    LENGTH(articles.body) ASC
;