使用子查询生成新列

Generating new columns with subqueries

我有两个表,imports 和 importrows。 importrows 包含有关导入中每个条目的所有信息。我假设这可以通过子查询实现。

导入行

import_id  | status

0001       | success

0001       | error

0001       | success

0001       | error

0002       | success

0003       | success

0001       | success

0001       | success

0001       | error

0003       | error

进口

import_id      |  created
    
    0001       | 2015-01-21 10:39:53
    
    0002       | 2015-01-21 10:39:53
    
    0003       | 2015-01-21 10:39:53

我想将这两个表加在一起形成如下形式:

import_id      |  created             | success | error
    
    0001       | 2015-01-21 10:39:53  |    4    |   3
    
    0002       | 2015-01-21 10:39:53  |    1    |   0
     
    0003       | 2015-01-21 10:39:53  |    1    |   1

您需要 JOIN 和 GROUP BY 操作

select
  i.import_id,
  i.created,
  s.success,
  e.error
from 
  imports i
join
  (select import_id, count(*) as success from importrows where status='success' group by import_id) s on s.import_id=i.import_id
join
  (select import_id, count(*) as error from importrows where status='error' group by import_id) e on e.import_id=i.import_id
select i.import_id,i.created,s.success,e.error from imports i left join (select import_id, count(*) as success from importrows where status='success' group by import_id) s on s.import_id=i.import_id left join (select import_id, count(*) as error from importrows where status='error' group by import_id) e on e.import_id=i.import_id    

做一个 left join 和 group by,这样如果你没有 'success' 或 'error' 用于特定的导入,它仍然是显示。