在mysql的IF中使用LIKE

时间:2012-09-27 20:14:47

标签: mysql sql-like

我正在尝试在mySQL的IF子句中使用LIKE并收到错误。

SELECT nc.web_name AS company_name,
    IF((b.booth_number LIKE '%Cafe%', b.booth_number, substring(b.booth_number,4)) AS booth_number, 
    nc.site_url AS website, IF (nc.ismi_status = 1, 'Member','') AS member_status 
    FROM booth_sale bs JOIN {ismi.booth} b ON bs.booth_id = b.booth_id 
    JOIN ismi.new_people np ON bs.contact_id = np.id 
    JOIN ismi.new_company nc ON nc.id = np.company_id 
    WHERE b.show_event_id = 298 AND status IN(44,45) ORDER BY 3

如果我这样做,查询工作正常:

IF((b.booth_number = 'Cafe', b.booth_number, substring(b.booth_number,4)) AS booth_number

但是我需要检查多种可能性 - 可能有Cafe,Cafe1,Cafe2等,我想返回b.booth_number以获取该字段值包含Cafe的任何记录。

这是我得到的错误:

  

PDOException:SQLSTATE [42000]:语法错误或访问冲突:1064   您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'AS booth_number,nc.site_url AS网站,IF(nc.ismi_status = 1,   'Member','')'在第2行:SELECT nc.web_name AS company_name,   IF((b.booth_number LIKE'%Cafe%',b.booth_number,   substring(b.booth_number,4))AS booth_number,nc.site_url AS网站,   IF(nc.ismi_status = 1,'Member','')AS member_status FROM   {ismi.booth_sale} bs JOIN {ismi.booth} b ON bs.booth_id = b.booth_id   JOIN {ismi.new_people} np ON bs.contact_id = np.id JOIN   {ismi.new_company} nc ON nc.id = np.company_id WHERE b.show_event_id =   298 AND状态IN(44,45)ORDER BY 3

任何人都可以告诉我我做错了什么,或者是否还有其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:3)

您的IF语句有一个太多的空心括号。删除第一个,你应该是好的(当然,等待任何其他SQL错误):

...
IF(b.booth_number LIKE '%Cafe%', b.booth_number, substring(b.booth_number,4)) AS booth_number, 
...