I got 2 tables: Owners and Storage as below:
Table: owners
id | owner | box ---------------------------- 1 | Nick | [] 2 | Jack | [] 3 | Jane | []
Table: Storage
id | fruit | owner_id --------------------------- 1 | Apple | 1 2 | Apple | 3 3 | Banana | 2 4 | Banana | 1 5 | Banana | 1 6 | orange | 1 7 | Apple | 3 8 | Orange | 2 9 | Apple | 2
Question: Is there a query to get how many fruit in each owner’s box in result? Like:
Nick:[Apple:1,Banan:2,Orange:1] Jack:[Apple:1,Banan:1,Orange:1] Jane:[Apple:2,Banan:0,Orange:0]
I tried to join 2 tables but it return me hundreds of records that duplicated. Much appreciated if anyone could guide me out.
Advertisement
Answer
SELECT owners.id, JSON_OBJECTAGG(fruits.fruit, COALESCE(boxes.cnt, 0)) boxes FROM (SELECT DISTINCT fruit FROM Storage) fruits CROSS JOIN owners LEFT JOIN (SELECT owners.id, Storage.fruit, COUNT(*) cnt FROM owners JOIN Storage ON owners.id = Storage.owner_id GROUP BY owners.id, Storage.fruit) boxes ON owners.id = boxes.id AND fruits.fruit = boxes.fruit GROUP BY owners.id;