sql - How to include user in MySQL query? -


i have query returns list of every post exists, comments (concatenated), , how many likes has.

i include column that indicates whether or not user has upvoted/liked specific post. structure of relevant tables follows:

likes (id, elementid, googleid)
elements (id, googleid, time, title, body, type)
comments (id, elementid, googleid, body)

so how go through likes, determine if 1 of them has user's id (dynamically put query via node.js), , create column indicating simple true or false?

select e.id, e.time, e.title, e.body, e.type, c.comments, e.googleid, l.likecount elements e left join(     select elementid, group_concat(body separator '|-|') comments     comments     group elementid ) c on c.elementid = e.id left join (     select elementid, count(id) likecount     likes     group elementid ) l on l.elementid = e.id; 

add left join against likes, passing user's googleid join's on clause. if values join non-null, user has liked post. if null, user has not liked it.

note first subquery join unnecessary. can taken care of directly in select list, , adding other selected columns group by clause (actually isn't necessary in mysql owing default behavior of group lenience, habit in since other rdbms require it)

select   e.id,   e.time,   e.title,   e.body,   e.type,   -- can moved outer select   group_concat(c.body separator '|-|') comments,   e.googleid,   l.likecount,   -- conditional statement match non-nulls in   -- left joined likes table, indicating whether   -- user has liked post   case     -- has like, return true     when luser.id not null true     -- not have like, return false     else false   end userliked elements e -- convert plain left join instead of subquery left join comments c on c.elementid = e.id -- left join against likes, strictly matching user id left join likes luser   on luser.elementid = e.id   -- pass user id join condition.   , luser.googleid = <the user's id> left join (     select elementid, count(id) likecount     likes     group elementid ) l on l.elementid = e.id; -- put other columns group -- instead of left join subquery group   e.id,   -- mysql let without rest of these   -- practice use them. other rdbms   -- not allow them omitted...   e.time,   e.title,   e.body,   e.type,   e.googleid   likecount,   userliked 

if prefer go using subquery join group_concat(), may revert , remove outer group by, may not fast method.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -