2014-01-09 97 views
0

因此,我正在查找綁定到電子郵件和account_id的數據,如果沒有結果,則只查找account_id。下面的代碼正確執行此操作。使用SQL_CALC_FOUND_ROWS和UNION ALL選擇聲明

SELECT SQL_CALC_FOUND_ROWS account_id, email, latitude, longitude 
FROM call_module_location 
WHERE email = $email AND `account_id` = $account_id 
UNION ALL 
SELECT account_id, email, latitude, longitude 
FROM call_module_location 
WHERE FOUND_ROWS() = 0 AND `account_id` = $account_id 

但是我需要處理3的情況下,如果ID數據未發現爲好,在這種情況下,我應該通過電子郵件獲取數據:

SELECT SQL_CALC_FOUND_ROWS account_id, email, latitude, longitude 
    FROM call_module_location 
    WHERE email = $email AND `account_id` = $account_id 
    UNION ALL 
    SELECT account_id, email, latitude, longitude 
    FROM call_module_location 
    WHERE FOUND_ROWS() = 0 AND `account_id` = $account_id 
    UNION ALL 
    SELECT account_id, email, latitude, longitude 
    FROM call_module_location 
    WHERE FOUND_ROWS() = 0 AND email = $email"; 

但它不工作。任何解決方案?

回答

1
SELECT account_id, email, latitude, longitude 
FROM (SELECT 1 priority, account_id, email, latitude, longitude 
     FROM call_module_location 
     WHERE email = $email AND `account_id` = $account_id 
     UNION 
     SELECT 2 priority, account_id, email, latitude, longitude 
     FROM call_module_location 
     WHERE `account_id` = $account_id 
     UNION 
     SELECT 3 priority, account_id, email, latitude, longitude 
     FROM call_module_location 
     WHERE email = $email) u 
ORDER BY priority 
LIMIT 1 

也有可能,如果你添加SQL_CALC_FOUND_ROWSUNION第二查詢您的原始查詢會工作。