分组依据在边子查询中返回多行

时间:2018-12-03 15:35:38

标签: mysql database

我有一张看起来像这样的桌子

+-----+-----+-----+-----+
| mid | rtn | ip  | mtc |
+-----+-----+-----+-----+
| A   | 2   | ab  | acc |
| A   | 1   | ab  | qty |
| A   | 5   | ab  | rel |
| A   | 1   | cd  | rel |
| A   | 3   | cd  | qty |
| B   | 1   | ab  | acc |
| B   | 4   | ab  | rel |
| B   | 3   | ab  | qty |
| B   | 5   | cd  | acc |
| B   | 1   | cd  | rel |
+-----------------------+

我正在尝试为每个唯一的mid值的每个mtc计数,因此结果表如下所示:

+-----+-----------+------------+-----------+
| mid | qty_total | rel_total  | acc_total |
+-----+-----------+------------+-----------+
|  A  |     1     |      2     |    2      |
|  B  |     2     |      1     |    2      |
+------------------------------------------+

到目前为止,我遇到的查询有疑问:

select mid,
   (select count(*) from t_r where mtc = 'qty' group by mid) as 'qty_total',
   (select count(*) from t_r where mtc = 'rel' group by mid) as 'rel_total',
   (select count(*) from t_r where mtc = 'acc' group by mid) as 'acc_total'
from t_r
group by mid;

运行查询时,我得到

  

[21000] [1242]子查询返回多于1行

1 个答案:

答案 0 :(得分:1)

您可以通过使用联合查询来实现

select distinct mid, [qty_total].c, rel_total.c, acc_total.c
from t_r

left join 
(select count(*) c, mid from t_r where mtc = 'qty' group by mid) as  [qty_total]
ON t_r.mid = [qty_total].mid

left join 
(select count(*) c, mid from t_r where mtc = 'rel' group by mid) as [rel_total]
ON t_r.mid = [rel_total].mid

left join 
(select count(*) c, mid from t_r where mtc = 'acc' group by mid) as [acc_total]
ON t_r.mid = [acc_total].mid