1

This is a bit confusing so bear with me.

I have 3 tables:

p           ps            s
+----+      +----+----+   +----+
|id  |      |pid |sid |   |id  |
+----+      +----+----+   +----+
|1   |      |2   |1   |   |1   |
|2   |      |2   |2   |   |2   |
|3   |      |3   |1   |   |3   |
+----+      +----+----+   +----+

tbl ps is used to link records from p to s - p can be combined with more than one 's' record, hence the linking table.

In MySQL 4.1.25, I used the following query to retrieve all the data, including where 'p' didnt have a corresponding 's' record, even if 'p' wasn't linked at all:

select p.id, ps.pid, ps.sid, s.id from p left join ps on p.id=ps.pid s right join on ps.sid=s.id;

This worked fine and correctly returned:

+------+------+------+------+
|p.id  |ps.pid|ps.sid|s.id  |
+------+------+------+------+
|1     |null  |null  |1     |
|1     |null  |null  |2     |
|1     |null  |null  |3     |
|2     |1     |1     |1     |
|2     |2     |2     |2     |
|2     |null  |null  |3     |
|3     |3     |1     |1     |
|3     |null  |null  |2     |
|3     |null  |null  |3     |
+------+------+------+------+    

Now, however, the same query in MySQL 5.5 is producing this:

+------+------+------+------+
|p.id  |ps.pid|ps.sid|s.id  |
+------+------+------+------+
|null  |null  |null  |1     |
|null  |null  |null  |2     |
|null  |null  |null  |3     |
|2     |1     |1     |1     |
|2     |2     |2     |2     |
|null  |null  |null  |3     |
|3     |3     |1     |1     |
|null  |null  |null  |2     |
|null  |null  |null  |3     |
+------+------+------+------+    

As you can see, any 'p' record that does NOT appear in ps, is returned as a null value. It almost looks as though it may be favoring the right join over everything else.

Any thoughts on what changed here and how I can rectify it?

Unfortunately, the corrected query must work in both versions of MySQL - which is becoming more and more of a pain for me to be honest, but nothing I can do about it. Obviously, efficiency is key as theses tables contain 100's of records (ps contains 1000's) and I need to get the same result set in a little steps as possible.

Thanks for your time folks!

4

1 回答 1

1

我认为你想做的最好用这个查询来表达:

select p.id, ps.pid, ps.sid, s.id
from p cross join
     s left join
     ps
     on p.id=ps.pid s and ps.sid=s.id;

我怀疑早期版本的 MySQL 被破坏了。

于 2014-01-14T19:37:04.573 回答