0

I have a query like

SELECT 
    pf.id, pf.forwhom, pf.body,
    u.firstname, u.lastname, u.email

FROM prayerfeed pf 
    JOIN users u ON pf.user_id=u.id

WHERE pf.id=100;

And this returns the feed item pf that I want as well as the user that posted that item.

What I also need is the users name that responded to that feed item and I know their id, lets call it 2.

This doesn't work but it might explain what I need.

SELECT 
    pf.id, pf.forwhom, pf.body,
    u.firstname, u.lastname, u.email,
    ru.firstname, ru.lastname
FROM prayerfeed pf 
    JOIN users u ON pf.user_id=u.id
    SELECT FROM users ru WHERE id=2 
WHERE pf.id=834;

How do I go about this?

1
  • You do a second join exactly as the previous one for users Aug 22, 2016 at 19:03

1 Answer 1

1

You need an additional JOIN:

SELECT 
    pf.id, pf.forwhom, pf.body,
    u.firstname, u.lastname, u.email,
    u2.firstname, u2.lastname, u2.email

FROM prayerfeed pf 
    JOIN users u ON pf.user_id=u.id

    JOIN users u2 ON u2.id = 2

WHERE pf.id=100;

You can simply use the ON clause to filter the user that responded to the feed item, using the already known id value.

4
  • Yup that is it. I could swear I tried that. So simple but now I don't know what I did try and got wrong. Thanks
    – Paul
    Aug 22, 2016 at 19:08
  • @Shadow do you see a better way?
    – Paul
    Aug 22, 2016 at 19:14
  • 1
    @PaulNeale You can alternatively use a CROSS JOIN, but I doubt if this makes any difference performance-wise. Aug 22, 2016 at 19:15
  • Don't think that I have ever seen that option. Will look deeper at it even if it doesn't change anything.
    – Paul
    Aug 22, 2016 at 19:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.