简体   繁体   中英

count in group_concat in mysql in one query

I have one to many table relationship :

  • one user for multiple event
  • one event for multiple event_attribute

Now, I group by userId and want to know how many for each event attribute ?

Below is the data schema you can use:

To be more specific, this is the DB schema I am using:

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
);
CREATE TABLE `event` (
  `id` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);
CREATE TABLE `event_attr` (
  `id` int(11) NOT NULL,
  `att_name` varchar(45) DEFAULT NULL,
  `event_id` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
);
INSERT INTO `user` VALUES (1,'user1'),(2,'user2'),(3,'user3');
INSERT INTO `event` VALUES (1,'event1',1),(2,'event2',1),(3,'event3',1),(4,'event4',2),(5,'event5',2),(6,'event6',3);
INSERT INTO `event_attr` VALUES (1,'att1','1'),(2,'att2','1'),(3,'att3','1'),(4,'att1','2'),(5,'att2',NULL);

Now if I am running:

select u.id, group_concat(e.name)
from user u 
join event e on u.id=e.user_id 
group by u.id

I will get:

1 event1,event2,event3
2 event4,event6
3 event 6

That is fine. But one step forward, I need to know count for each event_attt for each user, such as:

1 evet_att1:3;event_att2:2
2 event_att3:1

Then it is not possible. Can I use just one query to get above expected response?

We can try aggregating the event table first by both user and event, to generate the counts:

SELECT u.id, GROUP_CONCAT(e.name, ':', CAST(e.cnt AS CHAR(50)))
FROM user u 
LEFT JOIN
(
    SELECT id, name, user_id, COUNT(*) AS cnt
    FROM event
    GROUP BY id, name, user_id
) e
    ON u.id = e.user_id
GROUP BY
    u.id;

Demo

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