Jump to content

Archived

This topic is now archived and is closed to further replies.

emehrkay

mysql if statement

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

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites
thanks ober, but i figured it out. i just needed prens around the subquery and its working as expected

Share this post


Link to post
Share on other sites

×

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.