2014-10-10 225 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`