如何连接两个匹配唯一列ID的表?

时间:2016-03-15 11:59:42

标签: mysql sql

以下是我的代码。

select cserv.cust_id,serv.service_id,serv.service_name,cserv.cust_id,cserv.channel_id,cserv2.cust_id,cserv2.channel_id
from services as serv
left join cust_services as cserv on serv.channel_a=cserv.channel_id
left join cust_services as cserv2 on serv.channel_b=cserv2.channel_id
where cserv.cust_id IS NOT NULL
order by cserv.cust_id

以下是通过此查询生成的结果的图片。

enter image description here

以下是问题的图像。问题标有红色。

enter image description here

我想删除突出显示的记录。我怎样才能做到这一点?请帮帮我。

下面是我的服务表和cust_service表的图片。

服务表: -

enter image description here

cust_service: -

enter image description here

1 个答案:

答案 0 :(得分:0)

我已经使用您的数据集进行了测试,它似乎提供了您正在寻找的输出:

SELECT MIN(cserv.cust_id) AS cust_id1
      ,MIN(serv.service_id) AS service_id
      ,serv.service_name
      ,MIN(cserv.cust_id) AS cust_id2
      ,MIN(cserv.channel_id) AS channel_id
      ,cserv2.cust_id
      ,cserv2.channel_id
FROM services as serv
    LEFT JOIN cust_services AS cserv ON serv.channel_a=cserv.channel_id
    LEFT JOIN cust_services AS cserv2 ON serv.channel_b=cserv2.channel_id
WHERE cserv.cust_id IS NOT NULL
GROUP BY serv.service_name
        ,cserv2.cust_id
        ,cserv2.channel_id
ORDER BY cust_id1, service_id

这是OP的sqlfiddle和我的答案,各自的输出:http://sqlfiddle.com/#!9/74bc16/2

注意,我更改了cust_id字段的名称,因为它们导致字段模糊错误,因为它们都被命名为相同的东西。现在它们被标记为cust_id1cust_id2,因此您可以按顺序进行排序和排序。我还在service_id子句中添加了ORDER BY,以便保留原始示例中的顺序;你可以选择通过其他东西订购。