将三个 SQL 查询合并为一个

Combining three SQL queries into one

我从三个查询中获得了工作代码,但我想将它们合并为一个或两个。基本上,我正在检查所提供的 phone 号码是否存在于 table 联系人或潜在客户中,以及它是否作为辅助号码存在于自定义字段值中(尽管并非所有潜在客户都有自定义字段值)。我正在使用基于 CodeIgniter 的 CRM 系统。

我想做什么(non-correct/hypothetical查询):

SELECT * FROM contacts OR leads WHERE phonenumber = replace(X, '-', '')
OR leads.id = customvaluefields.relid AND cfields.fieldid = 41 AND cfields.value = X

表格

table : contacts
+-------+----------------+----------------+
|   id  |   firstname    |  phonenumber   |
+-------+----------------+----------------+
|   1   |      John      |   214-444-1234 |
|   2   |      Mary      |   555-111-1234 |
+-------+----------------+----------------+

table : leads
+-------+-----------+---------------------+
|   id  |   name    |     phonenumber     |
+-------+-----------+---------------------+
|   1   |   John    |   214-444-1234      |
|   2   |   Mary    |   555-111-1234      |
+-------+-----------+---------------------+

table : customvaluefields
+-------+-----------+-------------+-----------+
|   id  |   relid   |   fieldid   |   value   |
+-------+-----------+-------------+-----------+
|   1   |     1     |     41      | 222333444 |
|   2   |     1     |     20      | Management|
|   3   |     2     |     41      | 333444555 |
+-------+-----------+-------------+-----------+

如果我明白你在做什么,也许 UNION ALL 会起作用。这是让您入门的东西:

SELECT C.ID, C.FirstName, C.Phonenumber 
FROM Contacts C 
JOIN CustomValueField CVF 
ON c.ID = CVF.RelID AND 
    CVF.ID = 41
    AND REPLACE(Phonenumber,'-','') = cvf.Value 
UNION ALL 
    SELECT L.ID, L.FirstName, L.Phonenumber 
FROM Leads L
JOIN CustomValueField CVF 
ON L.ID = CVF.RelID AND 
    CVF.ID = 41
    AND REPLACE(Phonenumber,'-','') = cvf.Value 

我在每个查询中将联系人和引导表连接到 CustomeValueField,然后将它们与每个查询中的 WHERE 子句一起 UNION。我确定它不是 100% 适合您的需要,但应该让您找到解决方案。这里有更多信息:https://dev.mysql.com/doc/refman/8.0/en/union.html