mysql - SQL 查询在 SQLite 中有效,但在 MySQL 中无效

标签 mysql sqlite

我有以下查询在 SQLite 中有效但在 MySQL 中无效

select t.range as [range], count(*) as frequency                        
  from (select case
                 when x.sum between 0.5 and 100 then '0.5 - 100'                
                 when x.sum between 100.5 and 1000 then '100.5 - 1000'        
                 when x.sum between 1000.5 and 2000 then '1000.5 - 2000'
               end as range                                                  
        from (select l.id, sum(i.price) sum                                     
                from lists l
                  join items i                                                  
                    on i.list_id = l.id                                         
                  join line_items li                                            
                    on li.item_id = i.id and li.reversal_id is null             
              group by l.id) x ) t                                             
group by t.range;

运行MySQL出现如下错误

ERROR 1064 (42000): 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 '[range], count(*) as frequency
from (select case
               when x.sum b' at line 1

最佳答案

这很容易修复。 MySQL 不将方括号识别为转义字符。您可以使用反引号或双引号:

select t.`range` as `range`, count(*) as frequency  

rangereserved word in MySQL因此您需要在整个查询过程中对标识符进行转义。

或者只是使用另一个不需要转义的名称,例如sum_range

您可以将查询简化为:

select (case when x.sum between 0.5 and 100 then '0.5 - 100'                
             when x.sum between 100.5 and 1000 then '100.5 - 1000'        
             when x.sum between 1000.5 and 2000 then '1000.5 - 2000'
        end) as sum_range,
       count(*) as frequency                                                 
from (select l.id, sum(i.price) sum                                     
      from lists l join
           items i                                                  
           on i.list_id = l.id join                                        
           line_items li                                            
           on li.item_id = i.id and li.reversal_id is null             
      group by l.id
     ) x
group by sum_range;

关于mysql - SQL 查询在 SQLite 中有效,但在 MySQL 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43576288/

相关文章:

php - 执行查询时创建多个初始值相同但表名不同的SQL表

php数据库检查id

mysql - 从 CSV 文件导入后,Pilcrow 出现在所有列值中 - MYsql

sqlite - 使用 RAISE 创建触发器

mysql - 如果找到的值少于 2 个,则忽略选择

mysql - 如何在 MySQL 中执行 "horizontal UNION"? (连接表格)

sql - 使用 Rails(ActiveRecord) 查询 2012 年的最后一行 + 2013 年的所有行 + 2014 年的第一行 - 最佳实践

mysql - 如果数据不保留在 sqlite 中特定外键的表中,如何在列中添加数据

java - 如何在 Android Studio 中从 CSV 文件导入时从 SQLite DB 中删除特殊字符?

java - 使用 Intellij 或 Maven 生成 SQLite 数据库进行单元测试?