Adding Username instead of User ID in a query

Let me start with SQL isn’t a strength or skill of mine, I know just enough to be dangerous - and by that I mean I can likely break a query faster than I can create one.

Here is the query that I have:

-- [params]
-- topic_id :topic_id

SELECT 
    user_id,
    post_number,
    raw,
    created_at,
    like_count
FROM posts
WHERE topic_id = :topic_id
ORDER BY post_number

The problem that I am running into is that when I run the query in the Community, it shows me a clickable User for user_id but when I export it, it’s just the ID, which isn’t as helpful if I am sending it to another person to follow up with folks. I think I need to use a join to do some magic, possibly. Anyone can help here?

1 Like

You can JOIN the users table to pull that info in. :+1:

-- [params]
-- topic_id :topic_id

SELECT 
    p.user_id,
    u.username,
    p.post_number,
    p.raw,
    p.created_at,
    p.like_count
FROM posts p
  JOIN users u ON u.id = p.user_id
WHERE p.topic_id = :topic_id
ORDER BY p.post_number
5 Likes

I knew there was a join needed :tada: Thank you @JammyDodger

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.