我的postgresql 9.1中有以下表格
表contact
:
contact_id phone mobile
1 123 456
2 111 222
3 333 123
4 222 444
表role
:
contact_fk exchange
7 1
8 2
1 4
5 5
2 4
4 5
我需要结果如:
contact_id phone mobile exchange
1 123 456 4
3 333 123 4
2 111 222 4
我想要移动字段数据位于任何其他联系人电话字段中的所有联系人数据,并且用户必须在交换4中,contact_role
表
仅供参考:联系表包含大约50k行,因此将联系表连接到自身需要花费很多时间,因此我们必须同时应用contact_role
条件。
答案 0 :(得分:0)
加入50k表和2列(其中contact_fk可能是主要的)不应该花费很长时间。
SELECT t1.contact_id, t1.phone, t1.mobile, t2.exchange
FROM contact as t1
JOIN role as t2 ON t1.contact_id = t2.contact_fk
WHERE t2.exchange = 4
或者如果您在交换列上有索引,这可能会更快:
SELECT t1.exchange, t2.contact_id, t2.phone, t2.mobile
FROM role as t1
JOIN contact as t2 ON t1.contact_fk = t2.contact_id
WHERE t1.exchange = 4
答案 1 :(得分:0)
以下是答案
select t1.contact_id,
t1.phone,
t1.mobile,
t2.phone,
t2.exchange
from contact t1
inner join (select contact_id,
mobile,
phone,
exchange
from contact, contact_role
where contact.contact_id = contact_fk
and exchange = 4
) t2
on t1.mobile = t2.phone
and t1.mobile != '';