How do you do many to many table outer joins?

后端 未结 5 1459
陌清茗
陌清茗 2020-12-29 08:56

I have 3 tables, foo, foo2bar, and bar. foo2bar is a many to many map between foo and bar. Here are the contents.

select * from foo
+------+
| fid  |
+----         


        
5条回答
  •  情话喂你
    2020-12-29 09:21

    Working it out, you can start with your select. Don't include columns you don't want to ultimately see.

    SELECT foo.fid, bar.value
    

    Then we can do the WHERE clause, which can see is just as you expressed it.

    SELECT foo.fid, bar.value  
    WHERE bar.zid = 30
    

    Now the tricky part to connect things together for our FROM clause, using LEFT JOINs because we want to see every fid, whether or not there are intermediate matches:

    SELECT foo.fid, bar.value  
    FROM foo  
    LEFT JOIN foo2bar ON foo.fid = foo2bar.fid  
    LEFT JOIN bar ON foo2bar.bid = bar.bid  
    WHERE bar.zid = 30
    OR bar.zid IS NULL
    

提交回复
热议问题