Mysql错误无效使用组功能

时间:2015-06-19 11:00:09

标签: mysql

    select
    c.investor_id as investorid,
    i.name as investor_name,
    inv_typ.name as type_of_investor,
    (select count(*) from investor_users where user_id=iu.user_id) as num_of_investors,
    (select count(*) from task_logs where campaign_id=c.id) as num_of_task_logs,
    c.updated_at as updated_date,
    c.call_date as calldate,
    a.name as admin_name,
    c.id as campaign_id
  from
    admins a,
    investors i,
    investor_types inv_typ,
    campaigns c,
    task_logs tl,
    campaign_statuses cs,
    investor_users iu
  where
    c.investor_id=i.id
    and i.investor_type_id=inv_typ.id
    and i.id=iu.investor_id
    and c.campaign_status_id = cs.id
    and c.assigned_to_admin_id = a.id
    and c.campaign_type_id = 1
    and c.campaign_status_id = (select id from campaign_statuses having id=c.campaign_status_id and cs.code ='CLOSED') and c.assigned_to_admin_id = 46
    and tl.campaign_id = c.id and max((select task_logs.task_status_id from task_logs having task_logs.campaign_id = c.id)) = 9
  order by c.call_date ASC

1 个答案:

答案 0 :(得分:0)

max()子句中有where

max((select task_logs.task_status_id
     from task_logs
     having task_logs.campaign_id = c.id)) = 9

这是对聚合函数的不当使用。代替:

(select max(task_logs.task_status_id)
 from task_logs
 where task_logs.campaign_id = c.id) = 9

这个明显的错误很容易被发现,因为它非常大胆。但是,您的查询将受益于以下内容:

  • 永远不要在FROM子句中使用逗号。 始终使用正确的显式JOIN语法。这是表达连接二十年的正确方法,因此现在是每个人都可以使用它的时候了。
  • 使用表别名,以便查询更容易编写和阅读。
  • 不要将having子句与where子句混淆。该子查询应该使用where