使用子查询生成新列

时间:2015-01-28 20:26:22

标签: mysql mysqli subquery

有两个表,导入和导入。 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

2 个答案:

答案 0 :(得分:0)

您需要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

答案 1 :(得分:0)

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    

执行左连接并按分组,如果您没有成功'或者'错误'对于特定导入,它仍然显示。祝好运!