是否可以从mysql中的别名中进行选择?

时间:2014-02-22 11:09:09

标签: mysql sql

我创建了一个名为tbl的表别名,我想从中进行选择。但我无法做到这一点。我知道我的代码不正确也没有优化,但我只是测试MySQL CASE

select
case
when exists (select username from tbl) then 'Username Exists'
else 'Username does not exist'
end
from (select 1 as id, 'bob' as username, 'pass' as password) as tbl

我收到错误:Table 'users.tbl' doesn't exist in database users

2 个答案:

答案 0 :(得分:3)

您有错误,因为查询中没有涉及物理表,因为tbl只是您创建的别名。 如果您只想测试您的用户名是否存在,请执行以下查询:

SELECT CASE
WHEN id = 1 THEN 'Username Exists' ELSE 'Username does not exist'
END
FROM (SELECT 1 AS id, 'bob' AS username, 'pass' AS password) AS tbl

答案 1 :(得分:1)

试试这个

select
     case
         when exists (select username from tbl where  username = 'bob' and  password = 'pass') then 'Username Exists'
     else 'Username does not exist'
     end as existanse_column
from  tbl
limit 1

DEMO HERE