mysql与同一个表的多个连接

时间:2014-03-12 07:18:24

标签: mysql left-join

我有一个表,列有日期,系统,硬度,电导率,tankno。

date        system  cond    hard   tankno

2014-01-04  HT  55.67   2.68    1
2014-01-05  HT  64.67   3.1     2
2014-01-10  HT  54.77   2.44    1
2014-01-10  HT  66.3    3.47    2
2014-01-18  HT  55.63   2.38    1
2014-01-18  HT  65.9    1.44    2
2014-01-24  HT  53.1    1.76    2
2014-01-28  HT  64.53   2.1     1

我想要这样的举报


Date         system    Tank 1 cond   Tank1 Hard      Tank 2 cond  Tank 2hard

2014-01-04    HT            55.67       2.68            NULL        NULL  
2014-01-05    HT            NULL        NULL            64.67       3.1
2014-01-10    HT            54.77       2.44            66.3        3.47
2014-01-18    HT            55.63       2.38            65.9        1.44
2014-01-24    HT            NULL        NULL            53.1        1.76
2014-01-28    HT            64.53       2.1              NULL       NULL

我正在使用这个sql:

select t1.date, t1.cond as tk1cond, t1.hard as tk1hard,
       t2.cond as tk2cond, t2.hard as tk2hard   
from systemvalue t1 left join systemavalue t2 
     on t1.date=t2.date 
     and t2.tankno='2' 
     and  t2.system='HT' 
     and month(t2.date)='01' 
     and year(t2.date)='2014' 
where t1.tankno='1' and t1.system='HT'
      and month(t1.date)='01' 
      and year(t1.date)='2014'

但是这个返回数据与tankno 1值可用的日期有关:


Date         system    Tank 1 cond   Tank1 Hard        Tank 2 cond  Tank 2hard

2014-01-04    HT            55.67       2.68               NULL        NULL  
2014-01-10    HT            54.77       2.44               66.3        3.47
2014-01-18    HT            55.63       2.38               65.9        1.44
2014-01-28    HT            64.53       2.1                NULL        NULL

如何修改sql以获取所有日期的数据

我希望所有日期都来自日期列,并将其加入所有tank 1 vlaues和tank 2值

1 个答案:

答案 0 :(得分:0)

你在这里:

select 
    dt.date, 
    t1.cond as tk1cond, 
    t1.hard as tk1hard,
    t2.cond as tk2cond, 
    t2.hard as tk2hard  
from (select date from systemvalue group by date) dt
left join systemvalue t1 on t1.date = dt.date and t1.tankno = '1' and t1.system = 'HT'
left join systemvalue t2 on t2.date = dt.date and t2.tankno = '2' and t2.system = 'HT'