需要帮助编写查询(重组表)

ar5n3qh5  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(206)

我需要写一个select语句,用下面的方式重写这个表。。。我不知道如何使用mysql来实现这一点。
表格示例

user_id   date         a    b    c     
123456    2020-01-01   1    1    1
234567    2020-03-04   1    0    0
453576    2020-05-05   1    0    1

期望结果

user_id   date        results
123456    2020-01-01  a
123456    2020-01-01  b
123456    2020-01-01  c
234567    2020-03-04  a
453576    2020-05-05  a
453576    2020-05-05  c
liwlm1x9

liwlm1x91#

在mysql中,您可以使用 union all ,正在筛选 1 价值观:

select user_id, date, 'a' as result from mytable where a = 1
union all select user_id, date, 'b' from mytable where b = 1
union all select user_id, date, 'c' from mytable where c = 1
order by user_id, date, result
wfauudbj

wfauudbj2#

如果您有大量的数据,或者您的“表”实际上是一个复杂的查询(比如子查询或视图),那么使用 cross join 比使用 union all :

select t.user_id, t.date, r.result
from t cross join
     (select 'a' as result union all
      select 'b' as result union all
      select 'c' as result 
     ) r
where (t.a = 1 and r.result = 'a') or
      (t.b = 1 and r.result = 'b') or
      (t.c = 1 and r.result = 'c') ;

对于一个较小的表,性能可能并不重要。

相关问题