【问题标题】:Subquery in select after group-by分组后选择中的子查询
【发布时间】:2013-06-14 18:34:19
【问题描述】:

我想显示在整个数据库中至少使用了 10 次的数据类型的名称,以及它们使用的不同表的数量,按后者排序。在修修补补时,我到了这一点:

select data_type, count(distinct table_name) "count"
from all_tab_cols
group by data_type
having count(*) >= 10
order by "count" desc;

有输出

VARCHAR2 1920
NUMBER   1435
...

这是错误的,因为视图等都包括在内,而我在数据库中只有 125 个表。 但是,如果我尝试

select data_type, (select count(distinct t.table_name)
                   from all_tables t
                   where t.table_name in table_name) "count"
from all_tab_cols
group by data_type
having count(*) >= 10
order by "count" desc;

我明白了

LONG         125
SDO_GEOMETRY 125
... and so on

这也是错误的。显然这是因为子查询,更具体地说是where 子句。我以为table_name 只包含当前组的表名?我的想法有什么问题吗?你会如何解决这个问题?

FWIW,这是作业,所以一些粗略的指示就足够了。 我们正在使用互联网电影数据库的克隆。

【问题讨论】:

    标签: mysql sql group-by subquery


    【解决方案1】:

    我会加入 all_tab_columnsall_tables - 这将过滤掉非表格信息:

    select data_type, count(distinct table_name) "count"
    from all_tab_cols
    inner join all_tables using (owner, table_name)
    group by data_type
    having count(*) >= 10
    order by "count" desc;
    

    我在这里使用了“自然连接” (using ...),因为它更容易:)

    【讨论】:

    • 我曾经考虑过,但出于某种原因放弃了它。太棒了!但是您能解释一下为什么我的解决方案似乎不起作用吗?
    • 可能是子查询中的where t.table_name in table_name。我不太清楚它在做什么,所以我很自然地怀疑它:)
    • 我希望它只会让那些被 data_type 引用的表通过,因此在 select 语句中的 table_names 中有一个列,所以我可以在其中使用 in 对其进行测试一个子查询。似乎不起作用,而且比您建议的要丑得多。
    猜你喜欢
    • 2019-01-11
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    相关资源
    最近更新 更多