我有两个mysql查询返回一列电话号码。我想尝试最终得到一个列表中的电话号码列表,但不会出现在另一个列表中。
所以我的两个查询是:
SELECT phone
FROM civicrm_phone phone
LEFT JOIN civicrm_participant participant
ON phone.contact_id = participant.contact_id
WHERE phone.is_primary = 1
AND participant.id IS NULL
和
SELECT phone
FROM civicrm_phone phone
LEFT JOIN civicrm_participant participant
ON phone.contact_id = participant.contact_id
WHERE phone.is_primary = 1
AND participant.id IS NOT NULL
在有人要求之前,上述两个查询不提供互斥结果(基于对最后一个WHERE语句使用IS NULL和IS NOT NULL),因为我们在数据库中有相关个人使用相同的电话号码,但并不一定都有参与者.id。
感谢您的帮助。
答案 0 :(得分:4)
以下查询将第二个查询放在WHERE子句中进行比较:
SELECT phone
FROM civicrm_phone phone
LEFT JOIN civicrm_participant participant ON phone.contact_id = participant.contact_id
WHERE phone.is_primary = 1
AND participant.id IS NULL and
not exists (SELECT 1
FROM civicrm_phone phone2
LEFT JOIN civicrm_participant participant ON phone2.contact_id = participant.contact_id
WHERE phone.is_primary = 1
AND participant.id IS NULL
and phone2.phone = phone.phone
)
通常在SQL中,你会使用NOT IN,但带有相关子查询的NOT EXISTS在MySQL中效率更高。