过滤数据与没有连接的另一个表进行比较

时间:2017-09-13 05:17:17

标签: mysql sql

此查询:

select a.* , u.firstn, u.lastn,  u.Extension
from jfi.ambitiontempdata a
inner join jackson_id.users u
on a.Extension = u.Extension;

拉出我为CSR呼叫系统创建的大量记录,显示呼叫记录,呼叫号码和发起呼叫的号码等。

这很好用,但我需要再用另一段数据过滤它。

我有一个名为jfi.ambition_customer_data的表,它没有ID或任何东西可以在我现有的查询中加入它。但是,我需要运行上面的查询并检查jfi.ambition_customer_data表以查看每个表中是否存在某些电话号码。我从jfi.ambitiontempdata表中检查的数字取决于两个因素。

从上面的查询中,如果a.outbound = 1,则检查called_party中是否存在jfi.ambition_customer_data,如果a.outbound = 0是否存在,则检查calling_party是否存在。< / p>

以下是我的结果的屏幕截图供参考:

enter image description here

以下是来自customer表的数据,因此需要将上述调用字段与此表中的“Phone”进行比较:

enter image description here

那么如何过滤我的选择数据以确保我只获取客户表中可能存在2个不同数字的记录,具体取决于呼叫类型?

2 个答案:

答案 0 :(得分:1)

我认为,简单的联合就足够了,而且可能更容易理解:

select a.* FROM ambitiontempdata a
inner join customer c on a.called_party = c.phone
where a.outbound = 1
UNION
select a.* FROM ambitiontempdata a
inner join customer c on a.calling_party = c.phone
where a.outbound = 0;

编辑

要将此简单地与您自己的查询相结合,您可以执行以下操作:

select a.* , u.firstn, u.lastn,  u.Extension
from jfi.ambitiontempdata a
inner join jackson_id.users u
on a.Extension = u.Extension
inner join jfi.ambition_customer_data c
on a.called_party = c.phone 
where a.outbound = 1
UNION
select a.* , u.firstn, u.lastn,  u.Extension
from jfi.ambitiontempdata a
inner join jackson_id.users u
on a.Extension = u.Extension
inner join jfi.ambition_customer_data c
on a.calling_party = c.phone 
where a.outbound = 0;

第二次编辑

这样更好吗?

SELECT ua.*, u.firstn, u.lastn,  u.Extension
FROM
(select a.* FROM ambitiontempdata a
inner join customer c on a.called_party = c.phone
where a.outbound = 1
UNION
select a.* FROM ambitiontempdata a
inner join customer c on a.calling_party = c.phone
where a.outbound = 0) ua 
INNER JOIN jackson_id.users u
on ua.Extension = u.Extension

答案 1 :(得分:0)

Select
  a.* , u.firstn, u.lastn,  u.Extension
  IF(a.outbound = 1,
     (select phone from jfi.ambition_customer_data where customerNumber = a.calling_party),
     (select phone from jfi.ambition_customer_data where customerNumber = a.called_party)
    )
From jfi.ambitiontempdata a
INNER JOIN jackson_id.users u
ON a.Extension = u.Extension;