mysql subquery senior classic example

Queries sector average wage is the lowest sector of Information
Act 1: first find the equivalent of the average wage and the minimum average wage department number, and then filter by matching the department table

SELECT d.*
FROM departments d
WHERE d.department_id=(
    SELECT department_id
    FROM employees
    GROUP BY department_id
    HAVING AVG(salary) =
    (
        SELECT MIN(a)
        FROM(
            SELECT AVG(salary) a,department_id
            FROM employees
            GROUP BY department_id
                 )b
    )
)

or

Method 2: Sort through direct LIMIT then find the lowest wage sector numbers, and then match the department table

SELECT d.*
FROM departments d
WHERE d.department_id=(
    SELECT department_id
    FROM employees
    GROUP BY department_id
    ORDER BY AVG(salary) ASC
    LIMIT 1
);

Query the average minimum wage sector and the information sector average wage
law: the department table and the table with the lowest average wage connect, and then query

SELECT d.*,a
FROM departments d
INNER JOIN(
    SELECT AVG(salary) a,department_id
    FROM employees
    GROUP BY department_id
    ORDER BY AVG(salary) ASC
    LIMIT 1
) b
ON d.department_id=b.department_id;

The highest average salary job query information

SELECT *
FROM jobs
WHERE jobs.`job_id`=(
    SELECT job_id
    FROM employees e
    GROUP BY e.job_id
    ORDER BY AVG(salary) DESC
    LIMIT 1
);

Query the average wage higher than the company average wage of some departments
of law: Finding the average wage higher than the company average wage of the table, and then connect the department table

    SELECT department_name
FROM departments d
INNER JOIN(
    SELECT AVG(salary),department_id
    FROM employees
    GROUP BY department_id
    HAVING AVG(salary)>(
        SELECT AVG(salary)
        FROM employees
    )
) a
WHERE d.department_id=a.department_id;

For more information check out the company manager of all employees in the table

SELECT *
FROM employees
WHERE employee_id IN(
    SELECT manager_id
    FROM employees
);

Queries that department in various sectors the highest salary in the minimum wage is how much

SELECT MIN(e.salary)
FROM employees e
WHERE e.department_id=(
    SELECT department_id
    FROM employees
    GROUP BY department_id
    ORDER BY MAX(salary) DESC
    LIMIT 1
)

For more information query manager sectors with the highest average salary: last_name, department_id, email, salary

SELECT e.last_name,e.department_id,e.email,e.salary
FROM employees e
INNER JOIN departments d
ON d.manager_id=e.employee_id
WHERE d.department_id=(
    SELECT department_id
    FROM employees
    GROUP BY department_id
    ORDER BY AVG(salary) DESC
    LIMIT 1
)

Guess you like

Origin blog.51cto.com/14437184/2438938