Thanks, but i finally found the problem. This is bug/lack-of-feature in MySQL, that does not allow nested JOIN statements. (
http://bugs.mysql.com/bug.php?id=1591 and bug 1674).
Rudy, you're right about the foreign key, however reality is a bit more complex than my example. But maybe you have a smart work around for this bug in MySQL (in Orcle it would have been trivial with exists/not exists and subselect, and i DB2 I assume eg 2 would have worked).
What I'm trying to do is the following, assuming table a is a list of students, c is a list of courses and b is the releation between the two. I want to query all students, and if they have taken a specific course return that name:
SELECT a.aid, a.name, IFNULL(c.name,'-')
FROM a
LEFT JOIN b ON a.aid = b.aid
LEFT JOIN c ON b.cid = c.cid
WHERE (c.cid IS NULL OR c.cid = X)
This will return all students not taking any courses at all (then c.cid will be null), and all students taking (at least) the X course. However (and the root of this problem in my application) all students taking other courses will not be fetched at all (since c.cid in that case will be something else than X). So I moved to the following instead:
SELECT a.aid, a.name, IFNULL(c.name,'-')
FROM a
LEFT JOIN (b
INNER JOIN c ON b.cid = c.cid AND c.cid = X)
ON a.aid = b.aid
Which works in an ANSI environment, but not in MySql
So the question is how I can get to the students taking other courses than X, and only return one row (so I can UNION this with my original SQL):
SELECT a.aid, a.name, IFNULL(c.name,'-')
FROM a
LEFT JOIN b ON a.aid = b.aid
LEFT JOIN c ON b.cid = c.cid
WHERE (c.cid IS NULL OR c.cid = X)
UNION
SELECT a.aid, a.name, '-'
FROM a
INNER JOIN b ON a.aid = b.aid
LEFT JOIN c ON b.cid = c.cid AND c.cid = X
WHERE c.cid IS NULL
This is very close, where the second SQL returns all students taking at least one course not being X. However, the problem in this case is that I would get multiple rows if a student take two or more courses not being X (could I use HAVING COUNT?), but more difficult is to avoid a student that takes both X and another course, he would be fetched in both statements.
So the question is how do I fetch ONE row for each student that takes at least one course, and does not take X???
Any idea?
Thx