Jump to content


Photo

mysql if statement


  • Please log in to reply
2 replies to this topic

#1 emehrkay

emehrkay
  • Staff Alumni
  • Advanced Member
  • 1,214 posts

Posted 03 May 2006 - 12:26 PM

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

#2 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 03 May 2006 - 12:34 PM

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

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)

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.

Info: PHP Manual


#3 emehrkay

emehrkay
  • Staff Alumni
  • Advanced Member
  • 1,214 posts

Posted 03 May 2006 - 12:39 PM

thanks ober, but i figured it out. i just needed prens around the subquery and its working as expected




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users