开发者

Is it possible to have "null rows" in SQL?

I am using MySQL. Let's say I have table A, B and C. Table A is a base table. Table B and C both have foreign keys to table A. However I want to pull out the rows so that the output would look something like this.

A | B    | C
----------------
1 | 1    | NULL
1 | 2    | NULL
1 | NULL | 1
1 | NULL | 2
2 | 3    | NULL
2 | NULL | 3

So when B no longer has any rows left for a certain key the query moves on to C and stop outputting rows for B. This seems like it should be simple, but I seem to be having trouble coming up with the way it should be done.

Also the title of the question pro开发者_如何学Cbably doesn't make sense, but I wasn't sure how to best describe the scenario.


Thinking about it, an OUTER JOIN isn't going to give you the output format you want. Try something like this:

SELECT a.id AS A, b.id AS B, NULL AS C
FROM tableA a
INNER JOIN tableB ON a.id = b.fid
UNION
SELECT a.id AS A, NULL AS B, c.id AS C
FROM tableA a
INNER JOIN tableC ON a.id = c.fid
ORDER BY 1


Absolutely, yes, LEFT JOIN is your sharpest knife.

SELECT A.*,B.*,C.* FROM A
LEFT JOIN B ON A.ID = B.REFID
LEFT JOIN C ON A.ID = C.REFID


You could use an outer join:

select a.id, b.id, c.id
from a
left join b on a.id = b.id
left jon c on a.id = c.id
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜