如何从子查询中只获取一行?
Posted
技术标签:
【中文标题】如何从子查询中只获取一行?【英文标题】:How to get just one row from a subquery? 【发布时间】:2017-05-09 12:17:35 【问题描述】:我有 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
你能帮帮我吗?
【问题讨论】:
那么所有其他行应该是什么? 【参考方案1】:你可以在里面使用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;
【讨论】:
GROUP BY
的使用无效,除非外部选择中的所有内容都依赖于 u.name。以上是关于如何从子查询中只获取一行?的主要内容,如果未能解决你的问题,请参考以下文章
从子查询中获取表名以在一行中用于 Oracle 中的删除/更新/插入子句