2017-04-23 78 views
1

我有以下查詢SQLite中而不是在MySQLSQL查詢工作在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 
+1

刪除括號 – splash58

+0

@ splash58居然有2個錯誤,你提到的支架和戈登·利諾夫指出的保留字的使用範圍 – sugaryourcoffee

回答

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; 
+0

快,口才非常有幫助 - 謝謝! – sugaryourcoffee

相關問題