如何在一次查询中左键连接两次或以其他方式获取结果列表中的数据?
我希望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") );