2016-04-12 78 views
2
IF語句

我有以下存儲過程:SET凡在MYSQL

CREATE DEFINER = `root` @` % ` PROCEDURE `getQuotesReport` (
    IN datebegin DATETIME, 
    IN dateend DATETIME, 
    IN userID INT 
) 
SELECT 
    q1.id, 
    q1.rate, 
    q1.insurer, 
    dealershipcompany.NAME AS 'dealershipName', 
    q1.createdAt, 
    STATUS.STATUS AS 'Status', 
    (SELECT 
    CONCAT_WS(" ", u2.firstName, u2.lastName) 
    FROM 
    quotelog 
    INNER JOIN USER u2 
     ON (quotelog.createdBy = u2.id) 
    WHERE quotelog.STATUS = 1 
    AND quotelog.quote = q1.id 
    GROUP BY q1.id) AS `creatorName`, 
    (SELECT 
    u2.ROLE 
    FROM 
    quotelog 
    INNER JOIN USER u2 
     ON (quotelog.createdBy = u2.id) 
    WHERE quotelog.STATUS = 1 
    AND quotelog.quote = q1.id 
    GROUP BY q1.id) AS `creatorRole`, 
    client.NAME AS 'clientName', 
    client.dob, 
    CONCAT_WS(" ", u1.firstName, u1.lastName) AS `brokerName` 
FROM 
    quoteq1 
    INNER JOIN CLIENT 
    ON client.id = q1.client 
    LEFT JOIN dealershipcompany 
    ON dealershipcompany.id = q1.dealershipCompany 
    INNER JOIN quotelog 
    ON quotelog.quote = q1.id 
    LEFT JOIN USER u1 
    ON u1.id = quotelog.assignedTo 
    LEFT JOIN USER u2 
    ON (quotelog.createdBy = u2.id) 
    INNER JOIN STATUS 
    ON STATUS.id = quotelog.STATUS 
WHERE quotelog.assignedTo = userID 
    AND (
    q1.createdAt BETWEEN datebegin 
    AND dateend 
) 
ORDER BY q1.createdAt DESC 

我要設置好取決於如果VAR用戶ID爲空或不是

例如,如果用戶ID爲NULL,我更換其中,使用以下語句:

WHERE q1.createdAt BETWEEN datebegin AND dateend 
在果殼

,我希望它看起來像這樣

IF NULL(userID) THEN SET WHERE q1.createdAt BETWEEN datebegin AND dateend 
ELSE SET WHERE quotelog.assignedTo = userID AND (q1.createdAt BETWEEN datebegin AND dateend) 

我不知道這是否可行在Mysql中,我嘗試了不同的方法,但總是得到語法錯誤。

回答

3

你可以使用:

... 
WHERE (quotelog.assignedTo = userID OR userID IS NULL) 
    AND (q1.createdAt BETWEEN datebegin AND dateend) 

如果userID提供將返回分配給指定的用戶行中,如果不將返回所有用戶。

第二個條件將根據日期範圍過濾記錄。


另一種方法是使用COALESCE

... 
WHERE quotelog.assignedTo = COALESCE(userID,quotelog.assignedTo) 
    AND (q1.createdAt BETWEEN datebegin AND dateend) 

如果quotelog.assignedTonullable

... 
WHERE COALESCE(quotelog.assignedTo,-1) = COALESCE(userID,quotelog.assignedTo,-1) 
    AND (q1.createdAt BETWEEN datebegin AND dateend) 

其中類似-1數量應爲無效userId

+1

哇,答案比我想象的要簡單,謝謝,這是正確的答案,但是因此告訴我等10分鐘來標記它。 – Medo

+0

實際上還存在一些小問題,如果用戶標識爲空,那麼只能獲得具有NULL值的用戶ID,並不會返回所有用戶。 – Medo