在mysql中附加逗号分隔的字符串时出现语法错误

时间:2014-02-26 14:33:32

标签: php mysql sql syntax-error

我有以下查询

SELECT diamondsList.*, dealers.* FROM diamondsList JOIN dealers ON diamondsList.dealerId = dealers.id WHERE price >= :minPrice AND price <= :maxPrice AND carat >= :minCarat AND carat <= :maxCarat AND clarity IN (SI2,VS1,SI1,VS2,VVS2,VVS1,IF,FL) AND color IN (J,H,D,E,F,G,I) AND diamondsType IN (BR,HS,CUS,RAD,AS,PRIN,OV,PS,MQ,EM)

但我收到错误

   {"error":"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FL) AND color IN (J,H,D,E,F,G,I) AND diamondsType IN (BR,HS,CUS,RAD,AS,PRIN,OV,P' at line 1"}

'FL附近有什么语法错误?

不是那个查询

SELECT diamondsList.*, dealers.* FROM diamondsList JOIN dealers ON diamondsList.dealerId = dealers.id WHERE price >= :minPrice AND price <= :maxPrice AND carat >= :minCarat AND carat <= :maxCarat

完美无缺。

3 个答案:

答案 0 :(得分:5)

  

我有一个字符串“SI2,VS1,SI1,VS2,VVS2,VVS1,IF,FL”我该怎么做

如果您有CSV格式的值,则需要FIND_IN_SET进行搜索。

更改:

clarity IN (SI2,VS1,SI1,VS2,VVS2,VVS1,IF,FL)

致:

find_in_set( clarity, 'SI2,VS1,SI1,VS2,VVS2,VVS1,IF,FL' )

看起来,查询的其他部分仍然存在同样的问题 您需要对这些部分应用相同的FIND_IN_SET

答案 1 :(得分:2)

您的字符串值必须在引号中:

IN (SI2,VS1,SI1,VS2,VVS2,VVS1,IF,FL)

应该是

IN ('SI2','VS1','SI1','VS2','VVS2','VVS1','IF','FL')

这适用于查询中的所有字符串(即检查其他IN()语句)

答案 2 :(得分:0)

您好Umer PLease使用以下查询

SELECT diamondsList.*, dealers.* FROM diamondsList 
  JOIN dealers ON diamondsList.dealerId = dealers.id 
WHERE price >= :minPrice AND price <= :maxPrice 
  AND carat >= :minCarat AND carat <= :maxCarat 
  AND clarity IN ("SI2","VS1","SI1","VS2","VVS2","VVS1","IF","FL") 
  AND color IN ("J","H","D","E","F","G","I") 
  AND diamondsType IN ("BR","HS","CUS","RAD","AS","PRIN","OV","PS","MQ","EM")

如果“SI2,VS1,SI1,VS2,VVS2,VVS1,IF,FL”是单个字符串,则不需要使用IN(),您只需使用LIKE运算符即可。

SELECT diamondsList.*, dealers.* FROM diamondsList 
  JOIN dealers ON diamondsList.dealerId = dealers.id 
WHERE price >= :minPrice AND price <= :maxPrice 
  AND carat >= :minCarat AND carat <= :maxCarat 
  AND clarity LIKE "SI2,VS1,SI1,VS2,VVS2,VVS1,IF,FL" 
  AND color IN ("J","H","D","E","F","G","I") 
  AND diamondsType IN ("BR","HS","CUS","RAD","AS","PRIN","OV","PS","MQ","EM")

'FL附近有什么语法错误? 答案是在FL之前,IF和IF是mySQL中的关键字。因此,当您将用户引用时,它将删除错误..

如果您有一个“SI2,VS1,SI1,VS2,VVS2,VVS1,IF,FL”字符串,并且您想在单个元素中找到它,那么请使用以下查询。

SELECT diamondsList.*, dealers.* FROM diamondsList 
  JOIN dealers ON diamondsList.dealerId = dealers.id 
WHERE price >= :minPrice AND price <= :maxPrice 
  AND carat >= :minCarat AND carat <= :maxCarat 
  AND FIND_IN_SET(clarity,"SI2,VS1,SI1,VS2,VVS2,VVS1,IF,FL")  
  AND FIND_IN_SET(color,"J,H,D,E,F,G,I") 
  AND FIND_IN_SET(diamondsType,"BR,HS,CUS,RAD,AS,PRIN,OV,PS,MQ,EM")

如果你还不明白,请随意提问。