2014-04-21 84 views
0

我需要找到員工Milo的最高工作經驗。這裏是我的表:如何在多個連接中使用聚合函數?

CREATE TABLE company (
    id INT   NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(250) NOT NULL 
); 

CREATE TABLE employee (
    id INT   NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(250) NOT NULL 
); 

CREATE TABLE company_employee (
    company_id INT NOT NULL, 
    employee_id INT NOT NULL, 
    hire_date DATE DEFAULT NULL, 
    resign_date DATE DEFAULT NULL, 
    FOREIGN KEY (company_id) REFERENCES company (id), 
    FOREIGN KEY (employee_id) REFERENCES employee (id) 
); 

而且我查詢它獲取米洛

的所有公司
SELECT 
    employee.name, company.name, company_employee.hire_date, 
    company_employee.resign_date, 
    (company_employee.resign_date - company_employee.hire_date) 
FROM company 
    JOIN company_employee 
    ON (company.id = company_employee.company_id) 
    JOIN employee 
    ON (company_employee.employee_id = employee.id) 
    WHERE employee.name = 'Milo' 

它返回

+------+--------------+-----------+-------------+-----------------+ 
| name | company_name | hire_date | resign_date | experience_days | 
+------+--------------+-----------+-------------+-----------------+ 
| Milo | IBM   |1997-04-17 | 1998-03-08 | 325    | 
| Milo | IBM   |2012-04-03 | 2014-02-15 | 683    | 
| Milo | IBM   |2000-08-10 | 2003-01-01 | 874    | 
+------+--------------+-----------+-------------+-----------------+ 

但我只需要一個記錄,最大的經驗

+------+-----+------------+------------+-----+ 
| Milo | IBM | 2000-08-10 | 2003-01-01 | 874 | 
+------+-----+------------+------------+-----+ 

UPD:

此查詢查找每個公司

SELECT 
    company.name, 
    COUNT(company_employee.employee_id) 
FROM company 
    LEFT JOIN company_employee 
    ON company.id = company_employee.company_id 
GROUP BY company.name 
HAVING COUNT(company_employee.employee_id) > 0; 

我可以簡化它的所有員工的數量?

回答

1

您不需要聚合功能(MAX),因爲您在這裏沒有聚合任何東西。

您可以再補充ORDER BYLIMIT條款,如:

ORDER BY experience_days DESC 
LIMIT 1 

整個查詢可能是大概是:

SELECT 
    employee.name, company.name, company_employee.hire_date, 
    company_employee.resign_date, 
    (company_employee.resign_date - company_employee.hire_date) as experience_days 
FROM company 
    JOIN company_employee 
    ON (company.id = company_employee.company_id) 
    JOIN employee 
    ON (company_employee.employee_id = employee.id) 
    WHERE employee.name = 'Milo' 
ORDER BY experience_days DESC 
LIMIT 1 

@Update

是可以簡化您的查詢。

首先,您可以使用JOIN而不是LEFT JOIN,因爲您正在尋找擁有員工的公司。

然後,因爲您已經只有公司員工(員工行必須存在與公司加入),您不需要使用HAVING條件。

SELECT 
    company.name, 
    COUNT(company_employee.employee_id) 
FROM company 
    JOIN company_employee 
    ON company.id = company_employee.company_id 
GROUP BY company.name; 
+0

如何在我的表中使用SUM函數。任何例子? – Finkelson

+0

SUM()'也是一個聚合函數,你想總結什麼? –

+0

如果我需要輸出所有公司並找到所有公司的員工數量,我應該寫什麼查詢? – Finkelson