SQL左边独立地连接两个表

时间:2014-09-13 10:56:22

标签: sql left-join

如果我有这些表格:

Thing
id | name
---+---------
1  | thing 1
2  | thing 2
3  | thing 3

Photos
id | thing_id | src
---+----------+---------
1  | 1        | thing-i1.jpg
2  | 1        | thing-i2.jpg
3  | 2        | thing2.jpg

Ratings
id | thing_id | rating
---+----------+---------
1  | 1        | 6
2  | 2        | 3
3  | 2        | 4

我如何加入他们来制作

id | name    | rating | photo
---+---------+--------+--------
1  | thing 1 | 6      | NULL
1  | thing 1 | NULL   | thing-i1.jpg
1  | thing 1 | NULL   | thing-i2.jpg

2  | thing 2 | 3      | NULL
2  | thing 2 | 4      | NULL
2  | thing 2 | NULL   | thing2.jpg

3  | thing 3 | NULL   | NULL

即,在每张桌子上同时左边加入,而不是在下一张桌子上加入?

This是我能得到的最接近的地方:

SELECT Thing.*, Rating.rating, Photo.src
From Thing
Left Join Photo on Thing.id = Photo.thing_id
Left Join Rating on Thing.id = Rating.thing_id

3 个答案:

答案 0 :(得分:2)

你可以通过联合获得你想要的结果,这似乎是最明显的,因为你从排名或照片中返回一个字段。

通过建立联接left join而不是inner joins来解决您的其他情况(没有任何一种情况)。您将获得排名为NULL, NULL的重复记录,照片。您可以通过将批次移动到子查询来对此进行过滤,并对主查询执行select distinct,但更明显的解决方案是将union all替换为union,这也会过滤掉重复项。更容易,更易读。

select
  t.id,
  t.name,
  r.rating,
  null as photo
from
  Thing t
  left join Rating r on r.thing_id = t.id
union
select
  t.id,
  t.name,
  null,
  p.src
from
  Thing t
  left join Photo p on p.thing_id = t.id
order by
  id,
  photo,
  rating

答案 1 :(得分:0)

MySQL不支持完全外部联接,所以你必须使用UNION来破解它:

这里是小提琴:http://sqlfiddle.com/#!2/d3d2f/13

SELECT *
FROM (
    SELECT Thing.*,
           Rating.rating,
           NULL AS photo
    FROM Thing
    LEFT JOIN Rating ON Thing.id = Rating.thing_id

    UNION ALL

    SELECT Thing.*,
           NULL,
           Photo.src
    FROM Thing
    LEFT JOIN Photo ON Thing.id = Photo.thing_id
) s
ORDER BY id, photo, rating

答案 2 :(得分:0)

以下是我提出的建议:

SELECT
  Thing.*,
  rp.src,
  rp.rating
FROM
  Thing
  LEFT JOIN (
    (
      SELECT
        Photo.src,
        Photo.thing_id AS ptid,
        Rating.rating,
        Rating.thing_id AS rtid
      FROM
        Photo
        LEFT JOIN Rating
          ON 1 = 0
    )
    UNION
    (
      SELECT
        Photo.src,
        Photo.thing_id AS ptid,
        Rating.rating,
        Rating.thing_id AS rtid
      FROM
        Rating
        LEFT JOIN Photo
          ON 1 = 0
    )
  ) AS rp
    ON Thing.id IN (rp.rtid, rp.ptid)