简体   繁体   中英

MySQL query to get total item number from table 2 to owner in table 1?

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.

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;

fiddle

SELECT owner, GROUP_CONCAT(CONCAT('(', fruit,',',c,')') SEPARATOR ';') as counts
FROM 
    (SELECT owner, owner_id, fruit, COUNT(*) as c FROM `storage` 
     JOIN owners ON owners.id = storage.owner_id
     GROUP BY fruit, owner_id) as t 
GROUP BY owner_id

The key here is the request in the parenthesis

SELECT owner_id, fruit, COUNT(*) as c FROM `storage` GROUP BY fruit, owner_id

which gives something like

owner_id | fruit  | c
---------------------
1        | apple  | 1
1        | banana | 2
1        | orange | 1

and you just do group concat with fruit and c columns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM