[英]MySQL Group_concat result IN given numbers
I'm trying to find out, if any number in a group_concat result is in a given set of numbers. 我试图找出是否group_concat结果中的任何数字在给定的数字集中。
This example data can be used to try it out: 此示例数据可用于尝试:
CREATE TABLE `events` (
`eventid` int(11) NOT NULL AUTO_INCREMENT,
`eventname` varchar(255) DEFAULT NULL,
PRIMARY KEY (`eventid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of `events`
-- ----------------------------
BEGIN;
INSERT INTO `events` VALUES ('1', 'my event');
COMMIT;
-- ----------------------------
-- Table structure for `events2groups`
-- ----------------------------
CREATE TABLE `events2groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`eventid` int(11) DEFAULT NULL,
`groupid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of `events2groups`
-- ----------------------------
BEGIN;
INSERT INTO `events2groups` VALUES ('1', '1', '5'), ('2', '1', '3'), ('3', '1', '1');
COMMIT;
-- ----------------------------
-- Table structure for `groups`
-- ----------------------------
CREATE TABLE `groups` (
`groupid` int(11) NOT NULL AUTO_INCREMENT,
`groupname` varchar(255) DEFAULT NULL,
PRIMARY KEY (`groupid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of `groups`
-- ----------------------------
BEGIN;
INSERT INTO `groups` VALUES ('1', 'group1'), ('2', 'group2'), ('3', 'group3'), ('4', 'group4'), ('5', 'group5');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
Then fire this query: 然后触发此查询:
SELECT GROUP_CONCAT(groups.groupid),
IF ( GROUP_CONCAT(groups.groupid) IN (1,2,3), 'yes', 'no' ) as isInGroup
FROM `events`
LEFT JOIN events2groups ON events.eventid = events2groups.eventid
LEFT JOIN groups ON events2groups.groupid = groups.groupid
GROUP BY events.eventid
the first result column shows, that the event has the groups 5, 3 and 1. The user has the groups 1, 2 and 3, so the 3 and the 1 match. 第一个结果列显示事件具有组5、3和1。用户具有组1、2和3,因此3和1匹配。 How can I query this to get the 'yes' from the IF?
我该如何查询以从IF中获得“是”?
Why use the group_concat()
results? 为什么要使用
group_concat()
结果? Just use conditional aggregation: 只需使用条件聚合:
SELECT GROUP_CONCAT(groups.groupid),
(case when max(groups.group_id in (1, 2, 3)) > 0 then 'yes' else 'no'
end) as isInGroup
FROM `events` LEFT JOIN
events2groups
ON events.eventid = events2groups.eventid LEFT JOIN
groups
ON events2groups.groupid = groups.groupid
GROUP BY events.eventid;
SELECT GROUP_CONCAT(groups.groupid),
GROUP_CONCAT(case when groups.groupid IN (1,2,3) then 'yes' else 'no' end) as isInGroup
FROM `events`
LEFT JOIN events2groups ON events.eventid = events2groups.eventid
LEFT JOIN groups ON events2groups.groupid = groups.groupid
GROUP BY events.eventid
;
result no,yes,yes 结果不,是,是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.