简体   繁体   English

不是单组组功能

[英]Not a single-group group function

I have some tables which basically look as follows: 我有一些表基本上如下:

TBL_USER
user_id - number
user_name - varchar

TBL_STUFF
stuff_id - number
stuff_user_id - number

I want to query for all user information including the number of "stuff" they have. 我想查询所有用户信息,包括他们拥有的“东西”的数量。 I was trying something like this: 我正在尝试这样的事情:

select user_id, user_name, count(stuff_id) 
  from tbl_user
  left outer join tbl_stuff on stuff_user_id = user_id
 where user_id = 5;

but I get an error which says "not a single-group group function" 但我得到一个错误,上面写着“不是单组小组的功能”

Is there some other way I should be doing this? 还有其他方法我应该这样做吗?

Well, you are missing the group function ;-) 好吧,你错过了小组的功能;-)

Try this: 试试这个:

select user_id, user_name, count(stuff_id) 
from tbl_user left outer join tbl_stuff on stuff_user_id = user_id
where user_id = 5
group by user_id, user_name;

The last line is the group by clause that tells Oracle to count all rows with the same user_id and user_name combination. 最后一行是group by子句,它告诉Oracle使用相同的user_id和user_name组合计算所有行。

You could also do it like this: 你也可以这样做:

select 
  user_id, 
  user_name, 
  (
    SELECT
        COUNT(*)
    FROM
        tbl_stuff
    WHERE 
        stuff_user_id = tbl_user.user_id

  ) AS StuffCount, 
from 
   tbl_user
where 
   user_id = 5;

One of your comments states that you don't want to include all the field present in a GROUP BY clause. 您的一条评论声明您不希望包含GROUP BY子句中的所有字段。

@Arion posted a correlated-sub-query re-factor that gives the same values. @Arion发布了一个相关子查询重新因子,它给出了相同的值。

The following query uses a standard (un-correlated) sub-query (inline-view) instead. 以下查询使用标准(不相关)子查询(内联视图) This is because using this inline-view structure can often perform correlated-sub-query equivilents. 这是因为使用此内联视图结构通常可以执行相关子查询等效项。 But, also, because I find them easier to maintain. 但是,因为我发现它们更容易维护。

WITH
  stuff_count
AS
(
  SELECT
    stuff_user_id  AS user_id,
    COUNT(*)       AS val
  FROM
    tbl_stuff
  GROUP BY
    stuff_user_id
)
SELECT
  tbl_user.user_id,
  tbl_user.user_name,
  stuff_count.val
FROM
  tbl_user
LEFT JOIN
  stuff_count
    ON stuff_count.user_id = tbl_user.user_id
WHERE
  tbl_user.user_id = 5;

NOTE: When the plan is generated, it only runs the sub-query for the user_id's necessary, not the whole table ;) 注意:生成计划时,它只运行user_id所需的子查询, 而不是整个表;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM