2017-08-28 81 views
0

我有一个用户表,其中我有三个字段ID,电子邮件,u_firstname,u_status 其中我必须在这个表上应用搜索与案例功能在哪里条件。如何申请与案件栏搜索

users table structure 
........................................................................... 
id email      u_firstname status(0=inactive,1=active) 
........................................................................... 
1  [email protected]  varun    1 
2  [email protected]    abc    0 

我写的以下查询,其中我已经使用的MySQL 的情况下功能,如果1被来自分贝然后活性会显示这样的,其工作原理是,如果已经来到0,那么不活动来作为字符串或

查询

SELECT `id`,`email`,`u_firstname`,case u_status when '0' then 'inactive' when '1' then 'active' end as status FROM `users` 

运行上面的查询我得到这个输出 来自用户的表结构后

........................................................................... 
id email      u_firstname status(0=inactive,1=active) 
........................................................................... 
1  [email protected]  varun    active 
2  [email protected]    abc    inactive 

在此之后,我必须在此表上应用搜索,假设我编写 ac或用户状态的任何首字母,那么我们将获得所有活动用户的列表。

我需要这个输出,当我是激活用户记录在搜索框中输入AC

........................................................................... 
    id email      u_firstname status(0=inactive,1=active) 
    ........................................................................... 
    1  [email protected]  varun    active 

我曾尝试下面的查询,但它没有给予任何记录。

SELECT `id`,`email`,`u_firstname`,case u_status when '0' then 'inactive' when '1' then 'active' end as status FROM `users` where `u_status` like 'ac%' 
+0

您不能在WHERE子句中使用别名,为什么不在程序逻辑中使用0和1? –

回答

1

您可以使用LIKE

SELECT t.* 
FROM (Your Query) t 
WHERE t.status LIKE 'ac%' -- for active 
//WHERE t.status like 'in%' -- for inactive 

%通配符基本上是这样的:没有或一切,而不是符号。

actkfkd LIKE 'ac%' -- TRUE 
atcdas LIKE 'ac%' -- FALSE 
ac  LIKE 'ac%' -- TRUE 
0

你必须过滤你的第一个查询的结果是:

SELECT * FROM 
(SELECT `id`,`email`,`u_firstname`,case u_status when '0' then 'inactive' when '1' then 'active' end as status FROM `users`) a 
where `status` like 'ac%' 
+0

上面的查询显示错误#1248 - 每个派生表都必须有自己的别名 –

+0

通过命名派生表“a'''来修复它 – CCH

0

我认为你应该使用别名status不是原来的u_status列。

`SELECT `id`,`email`,`u_firstname`, 
case u_status when '0' then 'inactive' 
       when '1' then 'active' end as status 
FROM `users` 
where `status` like 'ac%'