简体   繁体   中英

MySQL conditional select statement?

Okay, so I have a client who wants to output all information for a bunch of students in a system.

This output is to be imported into Excel to be manipulated.

So, my problem is that I would like to output all students' information from 4 tables

auditions scheduled auditions profiles audition times

So, the auditions table gets and entry linking any information there to the student WHEN the audition is recorded. Before that, there is no audition for them in the db.

So, I want to output one row for each student that says when their scheduled audition is, and then if they have had their audition already to import the information, but if not, to just leave the field blank.

I've got something like this so far

"SELECT ".$fields." FROM profiles p, auditions a, scheduled_auditions s, 
audition_times t WHERE p.id=t.id AND t.id=s.id AND a.id=p.id"

The problem is obvious. It's only going to output people who have auditions. So, how do I write a conditional select/where statement so to speak? I need to output this with one query so that it will work when I open it in excel.

Thanks guys. I'm stumped.

Have you considered using a LEFT OUTER JOIN ?

If you join tables A and B with an inner join, you only get rows that exist in A and B. If you use a LEFT JOIN you would get all of the rows in A. Some of those rows would have data from B if it existed. Otherwise those columns from B would be null.

EDIT: A LEFT JOIN B is logically equivalent to B RIGHT JOIN A - so do whatever makes the most sense in your head (Thanks Paul.).

You want to perform an outer join; an outer join returns results even when the joined records are null.

Specifically, specifying a LEFT OUTER JOIN in your case on the auditions tables will force all the students' records to be returned, even the ones without auditions.

Sounds like you just need an outer join, which is like a normal join, but where there is no matching key it will just return NULL for every field.

SELECT * 
FROM profiles p
LEFT OUTER JOIN audition_times t
ON p.id=t.id
LEFT OUTER JOIN scheduled_auditions s
ON t.id=s.id 
LEFT OUTER JOIN auditions a
ON a.id=p.id"

You need to use an outer join for this. Look at http://en.wikipedia.org/wiki/Join_(SQL)#Outer_joins

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM