【发布时间】:2017-02-09 22:24:21
【问题描述】:
以下查询几乎是正确的,只是它导致 list_taxonomies 表中的行重复。我只需要 list_taxonomies 表中的唯一行。我一直在努力解决一些解决方案,但似乎无法得到它。我已经在 items 表上尝试了 LEFT OUTER 和 INNER 连接。
任何帮助表示赞赏。
查询:
SELECT
lists.*,
json_agg(items ORDER BY items.id) AS _items,
json_agg(list_taxonomies ORDER BY list_taxonomies.type) AS taxonomy
FROM
lists
JOIN
list_taxonomies ON list_taxonomies.list_id = lists.id
JOIN
items ON items.list_id = lists.id
WHERE
lists.id = 3
GROUP BY
lists.id
当前结果:
{
"status": "success",
"data": [{
"id": 3,
"name": "tincidunt pede ac urna. Ut",
"description": "Lorem ipsum dolor sit amet, consectetuer adipiscing",
"created": "2016-08-24T12:00:00.000Z",
"updated": "2016-08-24T12:00:00.000Z",
"owner": 9,
"likes": 3,
"private": 0,
"location": "United States",
"nsfw": 0,
"_items": [{
"id": 2,
"name": "sem semper",
"description": "sollicitudin commodo",
"list_id": 3,
"type": 2,
"image": "http://fillmurray.com/",
"list_order": 6,
"created": "2016-08-24T05:00:00-07:00",
"link": "http://amazon.com"
}, {
"id": 14,
"name": "magna sed",
"description": "bibendum. Donec felis",
"list_id": 3,
"type": 2,
"image": "http://fillmurray.com/",
"list_order": 1,
"created": "2016-08-24T05:00:00-07:00",
"link": "http://google.com"
}],
"taxonomy": [{
"list_id": 3,
"taxonomy": "Art",
"type": 1
}, {
"list_id": 3,
"taxonomy": "Art",
"type": 1
}, {
"list_id": 3,
"taxonomy": "Art",
"type": 1
}, {
"list_id": 3,
"taxonomy": "Art",
"type": 1
}, {
"list_id": 3,
"taxonomy": "Art",
"type": 1
}, {
"list_id": 3,
"taxonomy": "Art",
"type": 1
}, {
"list_id": 3,
"taxonomy": "Art",
"type": 1
}]
}],
"message": "Retrieved list 1"
}
【问题讨论】:
-
尝试左连接
-
@McNets 我试过了,结果一样。
-
应该在物品内分类吗?因为双左连接应该可以工作。
-
@McNets 分类应该在数据内部,而不是在项目内部。上面返回数据的结构是正确的。
标签: sql postgresql join