如何在mysql select查询中选择静态值?

时间:2018-08-22 04:42:04

标签: mysql

我是mysql的新手,在这里我试图从数据库表中获取数据。

select id,txnid,amount,status from txn_details;

使用上述查询成功获取数据,但status列获得012,但我希望0failed1success,而2not processed

如何更改我的查询?

4 个答案:

答案 0 :(得分:4)

您可以使用case

select id, txnid, amount,
       case when status = 0 then 'failed'
            when status = 1 then 'success'
            else 'not processed'
       end as status
from txn_details;

答案 1 :(得分:2)

我们可以在SELECT列表中使用一个表达式。它可能是搜索的CASE表达式,例如

SELECT CASE t.status 
         WHEN 0 THEN 'failed' 
         WHEN 1 THEN 'success'
         WHEN 2 THEN 'not processed'
         ELSE 'unknown' 
       END AS status_name
     , t.status
     , t.amount
     , t.txnid
  FROM txn_details t

此方法符合ANSI-92标准,并且适用于大多数关系数据库。

还有其他一些MySQL特定的替代方法,例如ELT函数...

SELECT ELT(t.status+1,'failed','success','not processed') AS status_name 
     , t.status
     , t.amount
     , t.txnid
  FROM txn_details t

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_elt

答案 2 :(得分:0)

如果您希望维护的中心点(即,当新状态出现时,您不希望不重新编码所有查询),则可以创建一个状态表,并使用联接或子查询来获取值,或者您可以创建一个函数,例如

drop table if exists txn_details,txn_status;

create table txn_details(id int, txnid int, amount int , status int);
insert into txn_details values
(1,1,10,1),(2,1,10,2),(3,1,10,4);

create table txn_status (id int, statusval varchar(20));
insert into txn_status values
(1,'success'),(2,'not processed'), (3,'failed');

drop function if exists f;
delimiter $$

create function f(instatus int)
returns varchar(20)
begin
declare rval varchar(20);
return  (select
                case when instatus = 1 then 'success'
                        when instatus = 2 then 'not processed'
                        when instatus = 3 then 'failed'
                        else 'Unknown'
                end
             );


select t.*,coalesce(ts.statusval,'Unknown') status
from txn_details t
left join txn_status ts on ts.id = t.status;

select t.*,coalesce((select statusval from txn_status ts where ts.id = t.status),'Unknown') status
from txn_details t;

请注意在未找到状态的情况下使用合并。 两者都会产生这个结果

+------+-------+--------+--------+---------------+
| id   | txnid | amount | status | status        |
+------+-------+--------+--------+---------------+
|    1 |     1 |     10 |      1 | success       |
|    2 |     1 |     10 |      2 | not processed |
|    3 |     1 |     10 |      4 | Unknown       |
+------+-------+--------+--------+---------------+
3 rows in set (0.00 sec)

使用这样的功能

select t.*, f(status) as status
from txn_details t;

也会产生相同的结果。

当然,使用状态表或功能意味着您必须传达其可用性并强制其使用。

我还将考虑在txn_details中使用外键约束来减少未知值的数量,并制定适当的程序以阻止人们随意添加新的状态代码而无需进行变更控制

答案 3 :(得分:-1)

以下查询将起作用。它使用CASE ... END确定并返回虚拟列status的值。

SELECT id,txnid,amount,
    CASE
        WHEN status = 0 THEN 'failed'
        WHEN status = 1 THEN 'success'
        WHEN status= 2 THEN 'not processed'
    END AS status
FROM txn_details;
相关问题