请考虑下表:
CREATE TABLE `customer_identifiers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`phone` varchar(45) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueness` (`order_id`,`email`,`phone`),
KEY `email` (`email`),
KEY `order` (`order_id`),
KEY `phone` (`phone`),
KEY `CA` (`created_at`),
KEY `UA` (`updated_at`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
insert into dev.customer_identifiers(order_id,email,phone) values (1,'test@gmail.com','07444226373'),
(2,'test@gmail.com','0744422633'),
(3,'test2@gmail.com','07444226373'),
(4,'test3@gmail.com','07453456373'),
(5,'test4@gmail.com','07955226373');
如何将所有共享同一电子邮件或同一电话号码的订单ID分组?
所需的输出:
+----------+------------------------+--------------------------------+
| order_id | phone | mail |
+----------+------------------------+--------------------------------+
| 1,2,3 | 07444226373,0744422633 | test2@gmail.com,test@gmail.com |
+----------+------------------------+--------------------------------+
| 4 | 07453456373 | test3@gmail.com |
+----------+------------------------+--------------------------------+
| 5 | 07955226373 | test4@gmail.com |
+----------+------------------------+--------------------------------+
答案 0 :(得分:2)
SELECT * FROM
(
SELECT ci2.`order_id`,GROUP_CONCAT(ci2.`order_id`) AS `concats`,GROUP_CONCAT(DISTINCT ci2.`phone`) as phones,GROUP_CONCAT(DISTINCT ci2.`email`) as mails
FROM `customer_identifiers` ci1
INNER JOIN `customer_identifiers` ci2 ON ci1.`email` = ci2.`email` OR ci1.`phone` = ci2.`phone`
GROUP BY ci1.`order_id`
) AS tbl1
GROUP BY tbl1.`order_id`;
答案 1 :(得分:-1)
您应该做的是计算重复的行数:
SELECT
email,
phone,
COUNT(email) AS count_email,
COUNT(phone) AS count_phone
FROM customer_identifiers
GROUP BY email,phone
HAVING
COUNT(email)>1 OR COUNT(phone) > 1
您可以个性化返回您需要识别具有重复性的ID的列。
希望对您有帮助...