Jump to content

Recommended Posts

i want to join two tables - names and class_enrollment. the common column is person_id

i want to have a simple list, first_name, last_name etc, but if they are enrolled in that class i want the enrollment to return 1

so i was thinking that i could do something like this

SELECT
first_name, if(SELECT person_id FROM class_enrollment ce WHERE ce.person_id = n.person_id AND ce.class_id = 72, 1, 0) AS enrolled
FROM
names n

that is givin me the error
"You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT person_id FROM class_enrollment ce WHERE ce.person_id = n.person_id, 1, 0' at line 2"
and im not sure what i am doing wrong
any help, thanks
Link to comment
https://forums.phpfreaks.com/topic/8958-mysql-if-statement/
Share on other sites

You're looking for a subquery (and your version of MySQL has to support it so you can do it).

[code]SELECT first_name AS enrolled
FROM names n
WHERE person_id IN (SELECT person_id FROM class_enrollment ce WHERE ce.person_id = n.person_id AND ce.class_id = 72, 1, 0)[/code]

If your version of MySQL doesn't support subqueries, you can always run the subquery as a seperate query first and use the IN WHERE X IN clause with the ids grabbed from the first query.
Link to comment
https://forums.phpfreaks.com/topic/8958-mysql-if-statement/#findComment-32914
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.