產品表
|_id|name |
|---|------|
|3 |Laptop|
尺碼表
|_id|product_id|size|
|---|----------|----|
|5 |3 |15 |
|6 |3 |17 |
詢問:
select tp._id, tp.name, ts.size from test_product tp
left join test_size ts on tp._id = ts.product_id
group by tp._id, tp.name, ts.size
where tp._id = 3 limit 10 offset 0
電流輸出:
|_id|name |size|
|---|------|----|
|3 |Laptop|15 |
|3 |Laptop|17 |
預期產出
|_id|name |size |
|---|------|-------|
|3 |Laptop|[15,17]|
注意: 由于當前查詢,我獲得了同一產品的 2 條記錄,并且我的限制和偏移查詢邏輯變得錯誤并且沒有得到正確的計數。對于這種情況,我不太了解Postgres查詢。所以我需要解決這個問題,所以我的限制和偏移邏輯對于獲取資料是正確的,對于這個查詢,我的產品計數將為 1。
uj5u.com熱心網友回復:
使用array_agg ():
SELECT
tp._id,
tp.name,
ARRAY_AGG(ts.size ORDER BY ts.size) -- ORDER BY to get consistent results
FROM
test_product tp
LEFT JOIN test_size ts ON tp._id = ts.product_id
GROUP BY
tp._id,
tp.name
WHERE
tp._id = 3
LIMIT 10
OFFSET 0;
聚合中的 ORDER BY 是可選的,但一次又一次地獲得一致的結果總是很好的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/458866.html
標籤:sql PostgreSQL 左连接
