2014-10-10 233 views
0

如何在語句之間執行sql語句?在case語句中選擇語句sql

我試圖執行下面的查詢和獲取錯誤:

select *, 
case when 'trans_type' <> 'Stock' then 
lname else (select item_name from trans_i where id = a.id limit 0,1) end as lname 
from 'transaction' as a 

數據庫爲MySQL

錯誤:

Error Code: 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 'select item_name from trans_i limit 0,1 

PS:我使用的交易作爲表名的演示目的只是,它不是我的真實數據庫中的「交易」。

+1

你會得到什麼錯誤? – 2014-10-10 16:23:12

+0

'transaction'是一個保留字。嘗試使用反引號包裹它:''...從'事務'''。 – 2014-10-10 16:23:40

+1

試試這個:http://stackoverflow.com/questions/14885912/select-case-when-then-select – Divya 2014-10-10 16:27:18

回答

1

我覺得這應該是正確的說法。

select *, 
(case when trans_type <> 'Stock' then 
a.lname else (select item_name from trans_i ti where ti.id = a.id limit 0, 1) 
end) as 'lname' from transaction as `a`