我有两个表'Customer'和'CustomerCommuncation',它们有字段:
**Customer**
---------------------------------------------
|ID | FirstName | LastName |
| 1 | John | Menon |
| 2 | george | cool |
| 3 | John | Menon |
| 4 | george | cool |
| 5 | John | Menon |
**CustomerCommunication**
---------------------------------------------------------
|ID | CommValue | CustomerID |
| 1 | abc@gmail.com | 1 |
| 2 | abcd@gmail.com | 1 |
| 3 | 9000000000 | 1 |
| 4 | abcde@gmail.com | 1 |
| 5 | xyz@gmail.com | 2 |
| 6 | xyzw@gmail.com | 2 |
| 8 | 9000000000 | 3 |
| 9 | abcdef@gmail.com | 3 |
| 10 | 9000000000 | 5 |
| 11 | xyz@gmail.com | 4 |
这两个表可以统称为: 可以联系John menon:abc @ gmail.com,abcd @ gmail.com,abcde @ gmail.com 90亿。
两个客户在他们的名字,姓氏和至少一个CommValue是相似的 很简单,customerIDs 1,3和5很相似,因为它们具有相同的FirstName,LastName 并分享PhoneNumber 9000000000。
问题: 给出组中的customerID列表。我们必须找到CustomerID的联合 与集团内的客户类似。
例如,如果我们得到一个组(1,2),那么结果将是(3,4,5)
我编写的存储过程如下:
CREATE DEFINER= FUNCTION `stroredfunc`( custlist varchar(1000)) RETURNS varchar(10000)
{
begin
declare v_commvalue varchar(10000) default '';
declare v_LastName varchar(1000) default '';
declare v_firstname varchar(1000) default '';
declare v_result varchar(10000) default '';
select group_concat(Distinct c.FirstName SEPARATOR ',') as v_firstname,
group_concat(Distinct c.LastName SEPARATOR ',') as v_LastName,
group_concat(Distinct cc.CommValue SEPARATOR ',') as v_commvalue
from Customer as c inner join CustomerCommunication as cc
on cc.CustomerID=c.ID where FIND_INSET(c.ID,custlist);
select group_concat(distinct cc.CustomerID) into v_result from Customer as c inner join
CustomerCommunication as cc
on cc.CustomerID=c.ID where FIND_IN_SET(c.FirstName,v_firstname) and
FIND_IN_SET(c.LastName,v_LastName) and
FIND_IN_SET(cc.CommunicationValue,v_commvalue )
;
return v_result;
end
}
还有其他优化方法吗
答案 0 :(得分:0)
可能可以简化为单个SQL。
我假设你想要一个类似于每个命名id的id列表(即,1类似于3和5,而2类似于4): -
SELECT a.ID, a.FirstName, a.LastName, GROUP_CONCAT(DISTINCT b.Id)
FROM Customer a
INNER JOIN Customer b
ON a.FirstName = b.FirstName
AND a.LastName = b.LastName
AND a.Id != b.Id
INNER JOIN CustomerCommunication c
ON a.Id = c.CustomerID
INNER JOIN CustomerCommunication d
ON a.Id = d.CustomerID
AND c.CommValue = d.CommValue
WHERE a.Id IN (1,2)
GROUP BY a.ID, a.FirstName, a.LastName
关于SQL小提琴的例子: -