代码之家  ›  专栏  ›  技术社区  ›  Reid

SQL:为什么在一条语句中计算两个表的计数很慢?

  •  1
  • Reid  · 技术社区  · 6 年前
    select count(distinct ec.logicalid) from event_counts ec where ec.eventname = 'Searches'
    
    select count(a.logicalid) from sf_accounts a
    

    当我将查询合并为一个查询时,得到的结果相同,但运行需要两分钟:

    select count(distinct ec.logicalid),  count(distinct a.logicalid) from event_counts ec, sf_accounts a where ec.eventname = 'Searches'
    

    我是否遗漏了一些可以加快查询速度的内容?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Nathan Griffiths    6 年前

    因为您正在交叉连接那些表,在那里使用旧式连接。我猜你不知道会发生这种事, but you can read here on why you shouldn't use them

    我想你想要的是一张桌子上的结果。如果是,请使用子查询。

    select (
        select count(distinct ec.logicalid) 
        from event_counts ec 
        where ec.eventname = 'Searches'
       ) as firstcount, 
           (
        select count(a.logicalid) 
        from sf_accounts a
       ) as secondcount
    

    否则,请正确联接表

    select 
       count(distinct ec.logicalid) 
       ,count(a.logicalid)
    from event_counts ec
    inner join sf_accounts a on a.logicalid = ec.logicalid
    where ec.eventname = 'Searches'