如何从子查询中获取一行?

时间:2017-05-09 12:17:36

标签: mysql subquery query-optimization

我有6列的查询,我也希望获得其他表列的总和。

我希望子查询的结果在一行中但重复了。

select t.id, t.subject, t.created_at, u.name, l.name as l_name, 
ty.name as t_name
,(select sum(new) from statuses ) as new
,(select sum(open) from statuses) as open
,(select sum(close) from statuses) as close
,(select sum(`delete`) from statuses) as `delete`
 from tickets t 
 left join users u  on u.id=t.user_id
 left join levels l on l.id=t.level_id
 left join types ty on ty.id=t.type_id
你可以帮我吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用GROUP BY

select t.id, t.subject, t.created_at, u.name, l.name as l_name, 
ty.name as t_name
,(select sum(new) from statuses ) as new
,(select sum(open) from statuses) as open
,(select sum(close) from statuses) as close
,(select sum(`delete`) from statuses) as `delete`
 from tickets t 
 left join users u  on u.id=t.user_id
 left join levels l on l.id=t.level_id
 left join types ty on ty.id=t.type_id GROUP BY u.name;