2016-08-19 184 views
2

我得到了兩個MYSQL表,我不知道是否有任何聚合函數MYSQL array_agg()從PostgreSQL。MYSQL數組聚合函數像PostgreSQL array_agg

表1性能只有8條 表2記錄誰抓住了財產,所以有時可以爲同一財產1或N次,我得到這個QRY:

SELECT p.id, pcb.users_admin_id as uid 
FROM properties p 
INNER JOIN prop_captured_by pcb ON p.id = pcb.property_id 
-- GROUP BY p.id 

id uid 
200 1 
200 80 
202 1 
202 80 
211 1 
211 10 
211 81 
215 10 ... 

如果我使用GROUP BY部分我得到:

id uid 
200 1 
202 1 
211 1 
215 10 ... 

丟失users_admin_id的第一個值以外的任何其他數據。我知道我可以通過postgreSQL中的array_agg()函數實現我想要的結果,但我無法弄清楚如何在MYSQL上完成它。

這是我的願望。結果:

id uid 
200 1,80 //an array, I don't mind about the separator, could be anything. 
202 1,80 
211 1,10,81 
215 10 ... 

我已經試過UNION,GROUP BY,INNER JOIN ...沒有運氣... 任何指針?

UPDATE

我使用從這個傢伙的many to many relations。希望它對別人有用。我需要從第三個表添加用戶的名稱,所以最終的查詢看起來是這樣的:

SELECT p.id, group_concat(pcb.users_admin_id) as uid, group_concat(ua.name) as uin 
FROM properties p 
INNER JOIN prop_captured_by pcb ON p.id = pcb.property_id 
INNER JOIN users_admin ua ON ua.id = pcb.users_admin_id 
group by p.id; 

回答

8

你想用GROUP_CONCAT()像介紹JSON_ARRAYAGG()JSON_OBJECTAGG()

SELECT p.id, group_concat(pcb.users_admin_id) as uid 
FROM properties p 
INNER JOIN prop_captured_by pcb 
ON p.id = pcb.property_id 
group by p.id; 
+0

這對我的作品! –

5

我想你想要group_concat()

SELECT p.id, GROUP_CONCAT(pcb.users_admin_id) as uids 
FROM properties p INNER JOIN 
    prop_captured_by pcb 
    ON p.id = pcb.property_id 
GROUP BY p.id; 

這將產生一個逗號分隔的字符串,但與您在MySQL中獲得的數組非常接近。

0

MySQL的22年7月5日。既然你想要的用戶名,以及,你可以使用後者:

SELECT p.id, JSON_OBJECTAGG(pcb.users_admin_id, ua.name) as uin 
FROM properties p 
INNER JOIN prop_captured_by pcb ON p.id = pcb.property_id 
INNER JOIN users_admin ua ON ua.id = pcb.users_admin_id 
group by p.id; 

DB Fiddle