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

sc4hvdpw  于 2021-06-18  发布在  Mysql
关注(0)|答案(4)|浏览(361)
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\u title”产生结果,对“event\u subtitle”显示空结果,即使我有结果“event\u subtitle”的数据

hi3rlvi2

hi3rlvi21#

例如,代码“起作用”

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)

如果您的数据模型不是这样的,或者基于我的示例数据的输出不是您所期望的,请将示例数据和所需的输出作为文本添加到问题中。

blmhpbnm

blmhpbnm2#

检查此项:

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
lzfw57am

lzfw57am3#

我想知道你是否需要:

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;
6ovsh4lw

6ovsh4lw4#

你在写什么 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
                      ^^^^^^^^^^^

相关问题