1

i have the following select statement

SELECT
    a.firstname name,
    m.date time
FROM
    account a
    LEFT JOIN memberships m ON a.id = m.account_id
WHERE
    a.is_active = 1

i am trying check and see if the user has an active membership (there could be more than one, but one is all i need as proof) and if so then set the variable true or the id or something, if not then false (or null or whatever)

here is what i have so far

SELECT
    a.firstname name,
    p.date time
    m.id active_membership
FROM
    account a
    LEFT JOIN profile p ON a.id = p.account_id
WHERE
    a.id IN (SELECT DISTINCT account_id FROM memberships WHERE active = 1)
AND
    a.is_active = 1

so the results i am trying to get would be name, time, active_membership foo, 10:00, null bar, 14:00, 223(id or anything)

i got everything working accept for the where in part...

6
  • Does memberships have more than one column? Commented Jun 20, 2014 at 0:10
  • It seems you need EXISTS here. Commented Jun 20, 2014 at 0:10
  • ya membership has a lot more columns Commented Jun 20, 2014 at 0:13
  • You can always use a RIGHT JOIN to force only records that have an associated account to load. Commented Jun 20, 2014 at 0:14
  • @tadman that won't work, that will prevent the whole selection altogether Commented Jun 20, 2014 at 0:17

1 Answer 1

2

You need another LEFT JOIN.

SELECT
    a.firstname name,
    p.date time,
    IF(m.account_id IS NULL, "No", "Yes") active_membership
FROM account a
LEFT JOIN profile p ON a.id = p.account_id
LEFT JOIN (SELECT DISTINCT account_id
           FROM memberships
           WHERE active = 1) m ON a.id = m.account_id
WHERE a.is_active = 1
Sign up to request clarification or add additional context in comments.

5 Comments

Why can't you just LEFT JOIN memberships m ON a.id=m.account_id AND m.active=1?
Because if someone has multiple memberships, that will create multiple rows in the result.
You could use that, but then you need to add GROUP BY a.id at the end.
Nothing GROUP BY couldn't fix, but that's good observation.
I prefer to use DISTINCT in the subquery, because it makes the cross product in the JOIN smaller.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.