在MYSQL中的IF语句中设置WHERE

时间:2016-04-12 08:16:26

标签: mysql sql

我有以下存储过程:

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 userID是否为NULL

例如,如果userID为NULL,我将where语句替换为以下内容:

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中这是否可行,我尝试了不同的方法,但总是会出现语法错误。

1 个答案:

答案 0 :(得分: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