MySQL选择连接计数

时间:2013-10-21 14:04:05

标签: mysql

我正在尝试从视图中的多个表中获取数据列表以进行分析 - 大多数数据来自一个表,然后我需要从多个其他表中获取计数以显示登录数,用户数等等。

我使用以下查询(简化为仅显示一些行和一个连接):

Select 
    companies.company_name, companies.last_login, companies.last_ip,
    (SELECT COUNT(*) FROM auditing_master GROUP BY company_id) AS audit_count
From
    companies
Left Join
    auditing_master On auditing_master.company_id = companies.id 
Group by 
    companies.id

当我运行时,我收到一个错误:

#2014 - Commands out of sync; you can't run this command now

如果我在SELECT COUNT(*)中没有GROUP BY的情况下运行它,那么它不会给出任何错误,但它会返回auditing_master表中所有条目的计数,无论它引用哪个公司。

如何获得单个查询以向我显示公司表中所需的数据,同时还显示按公司ID分组的审计主数据(和其他数据)的总数?

修改

使用多个计数/联接时的代码:

Select 
    c.company_name, c.last_login, c.last_ip,
    COUNT(am.company_id) AS audit_count,
    COUNT(u.company_id) AS users,
    COUNT(e.company_id) AS employees
From
    companies c
Left Join
    auditing_master am On am.company_id = c.id 
Left Join
    users u On u.company_id = c.id 
Left Join
    employees e On e.company_id = c.id 
Group by 
    c.id

在WAMP上的PHPMyAdmin本地查询只有大约10家公司需要7秒才能完成并提供与任何事情无关的“无意义”结果。

由于

2 个答案:

答案 0 :(得分:2)

  1. SELECT子句中的内部查询必须返回单值结果
  2. 类似的东西,应该带来你需要的东西。

    Select 
        companies.company_name, companies.last_login, companies.last_ip,
        COUNT(*) AS audit_count  
    From  
        companies  
    Left Join  
        auditing_master On auditing_master.company_id = companies.id   
    Group by   
        companies.id  
    

答案 1 :(得分:1)

你尝试过这个吗? (不需要子查询,因为没有where子句,LEFT JOIN已添加按company_id = companies.id分组的auditing_master行

Select 
    companies.company_name, companies.last_login, companies.last_ip,
    COUNT(company_id) AS audit_count
From
    companies
Left Join
    auditing_master On auditing_master.company_id = companies.id 
Group by 
    companies.id

修改

如果您没有针对给定公司的auditing_master,可能会添加IF语句以避免COUNT。

SELECT
    companies.company_name, companies.last_login, companies.last_ip,
    IFNULL(am.company_id,0,COUNT(am.company_id)) AS audit_count
FROM
    companies
INNER JOIN
    auditing_master am ON auditing_master.company_id = companies.id 
GROUP BY
    companies.id

随意放置整个SQL ......因为问题可能在其他地方!