如何并排显示同一个表中的数据

use*_*071 2 php mysql sql database inner-join

假设我在mysql中有一个表(称为get),如下所示:

ID S Num
00 1 506
00 2 620
01 1 562
01 2 564
02 1 548
02 2 484
03 1 488
03 2 895
Run Code Online (Sandbox Code Playgroud)

我试图以这种格式得到它:

ID S1  S2
00 506 620
01 562 564
02 548 484
03 488 895
Run Code Online (Sandbox Code Playgroud)

到目前为止我有这个,但它给了我一个错误:

select id,d.S1,c.S2 from 
(select S as S1 from get where S=1)d inner join  
(select s as S2 from get where S=2)c using (id);
Run Code Online (Sandbox Code Playgroud)

我仍然不太确定加入,但这似乎有道理.

编辑:S有时只能有1个值,在这些时间内,此值将为S1

Tar*_*ryn 7

您可以使用自联接,换句话说,您可以在桌面上加入两次,类似于您的开始方式.既然您声明S=1将始终存在,那么您可以使用以下查询:

select t1.id,
  t1.num S1,
  t2.num S2
from yourtable t1
left join yourtable t2
  on t1.id = t2.id
  and t2.s = 2
where t1.s = 1;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo.S=1即使S=2表中不存在,在表上使用LEFT JOIN也将返回值为的所有行.

您还可以使用带有CASE表达式的聚合函数来获取结果:

select
  id,
  sum(case when s = 1 then num end) S1,
  sum(case when s = 2 then num end) S2
from yourtable
group by id;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo