簡體   English   中英

將三個 SQL 查詢合並為一個

[英]Combining three SQL queries into one

我從三個查詢中獲得了工作代碼,但我想將它們組合成一兩個。 基本上,我正在檢查提供的電話號碼是否存在於表格聯系人或潛在客戶中,以及它是否作為輔助號碼存在於 customfieldsvalues 中(但並非所有潛在客戶都有自定義字段值)。 我正在使用基於 CodeIgniter 的 CRM 系統。

我想要做什么(不正確/假設的查詢):

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 |
+-------+-----------+-------------+-----------+

當前工作查詢

$result = $CI->db->query('SELECT * FROM ' . db_prefix() . 'contacts 
            WHERE replace(replace(phonenumber, " ", ""), "-", "") = ' . $phonenumber)->row();

if (count($result) == 0) {
    $result = $CI->db->query('SELECT * FROM ' . db_prefix() . 'leads 
            WHERE replace(replace(phonenumber, " ", ""), "-", "") = ' . $phonenumber)->row();
            
    if (count($result) == 0) {
        $result = $CI->db->query('SELECT * FROM ' . db_prefix() . 'leads AS l 
            INNER JOIN ' . db_prefix() . 'customfieldsvalues AS c ON l.id = c.relid
            WHERE c.fieldid = 41 AND c.value = ' . $phonenumber)->row();
    }
}

如果我理解你想要做什么,也許 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 子句一起合並。 我確信它不是 100% 正確滿足您的需要,但應該讓您找到解決方案。 這里有更多信息: https://dev.mysql.com/doc/refman/8.0/en/union.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM