如何在一个查询中进行两次左连接?

时间:2016-04-13 10:33:53

标签: sql postgresql

如何在一次查询中左键连接两次或以其他方式获取结果列表中的数据?

我希望media_information下的media

{ 
  id: 9,
  gallery_id: 25,
  media_id: 9,
  media: { 
    id: 9,
    media_information: {
      id: 9,
      media_id: 9,
    }
  },
}

查询我试过

var dbQuery = `SELECT
  gm.*,
  row_to_json(m.*) as media,
  row_to_json(mi.*) as media_information
  FROM "gallery_media" gm 
  LEFT JOIN media m ON gm.media_id = m.id
  LEFT JOIN media_information mi ON gm.media_id = mi.media_id
  WHERE "gallery_id" = $1 
  ORDER BY gm.create_date DESC OFFSET $2 LIMIT $3`;

结果

{ 
  id: 9,
  gallery_id: 25,
  media_id: 9,
  media: { 
    id: 9,
  },
  media_information: {
    id: 9,
    media_id: 9,
  }
}

更新

我也尝试过更改ON m.id = mi.media_id,但结果没有任何变化

var dbQuery = `SELECT
  gm.*,
  row_to_json(m.*) as media,
  row_to_json(mi.*) as media_information
  FROM "gallery_media" gm 
  LEFT JOIN media m ON gm.media_id = m.id
  LEFT JOIN media_information mi ON m.id = mi.media_id
  WHERE "gallery_id" = $1 
  ORDER BY gm.create_date DESC OFFSET $2 LIMIT $3`;

CREATE TABLE IF NOT EXISTS "gallery_media"(
    "id" SERIAL NOT NULL,
    "gallery_id" integer NOT NULL,
    "media_id" integer NOT NULL,
    PRIMARY KEY ("id")
  );
CREATE TABLE IF NOT EXISTS "media"(
    "id" SERIAL NOT NULL,
    PRIMARY KEY ("id")
  );

CREATE TABLE IF NOT EXISTS "media_information"(
    "id" SERIAL NOT NULL,
    "media_id" integer NOT NULL,
    PRIMARY KEY ("id")  );

http://sqlfiddle.com/#!15/ff805

0 个答案:

没有答案