MySql-如何将两个别名设置为单列

时间:2018-12-03 09:43:04

标签: mysql sql

select event_id,
       IF(event_type!='C',e.event_title ,'') event_title,
       IF(event_type='C', e.event_title ,'') event_subtitle
from event e where log_id='%s'

此查询仅针对“ event_title”结果,即使我有结果“ event_subtitle”的数据,对于“ event_subtitle”也显示空结果

4 个答案:

答案 0 :(得分:1)

例如,代码“有效”

drop table if exists event;
create table event(event_id int, event_type varchar(1), event_title varchar(10));

insert into event values
(1,'c','aaa'),(2,'x','xxx');

select event_id,
       IF(event_type!='C',e.event_title ,'') event_title,
       IF(event_type='C', e.event_title ,'') event_subtitle
from event e;

+----------+-------------+----------------+
| event_id | event_title | event_subtitle |
+----------+-------------+----------------+
|        1 |             | aaa            |
|        2 | xxx         |                |
+----------+-------------+----------------+
2 rows in set (0.00 sec)

如果您的数据模型看起来不是这样,或者基于我的样本数据的输出不是您期望的,请以文本形式向问题中添加样本数据和所需的输出。

答案 1 :(得分:0)

检查此:

select event_id,
       case when event_type<>'C' then e.event_title  end  as  event_title,
       case when event_type='C'then e.event_title end as  event_subtitle
from event where log_id='%s';

示例:

SELECT ename ,
case when job='SALESMAN' then  ename end as  salesman_ename,
case when job<>'SALESMAN' then  ename end as not_salesman_ename
FROM scott.emp;

SMITH       SMITH
ALLEN   ALLEN   
WARD    WARD    
JONES       JONES
MARTIN  MARTIN  
BLAKE       BLAKE
CLARK       CLARK
SCOTT       SCOTT
KING        KING
TURNER  TURNER  
ADAMS       ADAMS
JAMES       JAMES
FORD        FORD
MILLER      MILLER
H       H

答案 2 :(得分:0)

您在两种情况下都写event_title,但是根据您的要求,我知道您想要IF(event_type='C', e.event_subtitle ,'') event_subtitle

更改自

IF(event_type!='C',e.event_title ,'') event_title,
IF(event_type='C', e.event_title ,'') event_subtitle

收件人

IF(event_type!='C',e.event_title ,'') event_title,
IF(event_type='C', e.event_subtitle ,'') event_subtitle
                      ^^^^^^^^^^^

答案 3 :(得分:0)

我想知道是否需要汇总:

select event_id,
       max(case when event_type <> 'C' then e.event_title end) as event_title,
       max(case when event_type = 'C' then e.event_title end) as event_subtitle
from event e
where log_id = '%s'
group by event_id;