开发者

MySQL conditional select statement?

开发者 https://www.devze.com 2023-03-11 07:48 出处:网络
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.

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 no开发者_如何学Pythont, 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.


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.


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!).


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

0

精彩评论

暂无评论...
验证码 换一张
取 消