XII subquery (very important to master essential)

A subquery

  Appear in the select statement select statement, called sub-query or within the query.

  External select query, called the outer query or the main query.

Second, the sub-query classification

  Press the number of rows of the result set divided into four kinds

  • Query scalar (one result set only one row)

  • Liezi query (result set only over one row)

  • Row subquery (result set has one row multi-column)

  • Table subqueries (usually the result set rows and columns)

  Different location subquery appears in the main query points

  • behind the SELECT : only supports standard quantum query.

  • back from : Support table subqueries.

  • or where rear HAVING : a scalar subquery supported (separate single line), column subquery (single multi-line), the row subquery (multiple rows and columns)

  • behind exists (ie, the relevant sub-query) : sub-table queries (multi-line, multi-column)

 

Third, the back of select sub-query

  Subqueries located behind select, and only supports standard quantum query .

  The number of employees in each department query:

  SELECT
    a.*,
    (SELECT count(*)
     FROM employees b
     WHERE b.department_id = a.department_id) AS 员工个数
  FROM departments a;

  Queries employee number 102 = Department Name:

  SELECT (SELECT a.department_name
            FROM departments a, employees b
            WHERE a.department_id = b.department_id
                   AND b.employee_id = 102) AS 部门名;

Four, from the back of the sub-queries  

  The sub-query result set to act as a table, which calls for aliases, not those who can not find the table.

  Then the real tables and sub-query results table join query.

  Queries wage level of the average wage in each sector:

  SELECT
    t1.department_id,
    sa AS '平均工资',
    t2.grade_level
  FROM (SELECT
            department_id,
            avg(a.salary) sa
          FROM employees a
          GROUP BY a.department_id) t1, job_grades t2
  WHERE
    t1.sa BETWEEN t2.lowest_sal AND t2.highest_sal;

Five, where the back and having a subquery  

  or where the back having, may be used

  1. Scalar subqueries (subquery single separate line)

  2. Column subquery (single multiple-row subqueries)

  3. Row subqueries (rows and columns) 

  Feature

  1. Subquery placed in parentheses.

  2. Subqueries general conditions on the right side.

  3. Scalar query, typically with the use of single-line operator, multi-line operators   >, <,> =, <=, =, <>,! = 

  4. Column subquery, generally with the use of multi-line operator    

    in (not in): the list of "arbitrary"

    any or some: Comparative subqueries and "a certain value" return, such as a> som (10,20,30), a subquery is greater than any one can, is greater than a minimum value to a subquery, equivalent to a > min (10,20,30).

    all: and subqueries "all values" returned comparison, such as a> all (10,20,30), a subquery is greater than all the values, in other words, the maximum value A is larger than the subquery query can be satisfied, equivalents, in a> max (10,20,30);

   The sub-query execution priority over the main query execution, because the condition of the main query uses the result of the subquery.

    mysql is in, any, some, all

    in, any, some, all sub-queries are one of the keywords.

    in : in the expression commonly used where its role is to query data within a certain range

    any and some as : may =,>,> =, <, <=, <> in combination, respectively, equal to, greater than, greater equal, less than, less than or equal, not equal to any of the data.

    All : may =,>,> =, <, <=, <> are used in combination, respectively, equal to, greater than, greater equal, less than, less than or equal, which is not equal to all the data therein.

    Hereinafter will often use these keywords.  

  Scalar query 

    General scalar query example: Query higher wages than Abel's Who?

    / * ① query abel wages [modified query is a scalar Query] * /
    the SELECT the salary
    the FROM the Employees
    the WHERE last_name =  'Abel';

    / * ② query employee information, meet salary> The results of ① * /
    the SELECT *
    the FROM the Employees A
    the WHERE A a .salary> (the SELECT the salary
                          the FROM the Employees
                          the WHERE last_name =  'Abel');
  

    A plurality of scalar queries Example: job_id and return the same 141 employees, salary employees more than 143 workers, name, salary and job_id

    /*③查询员工的姓名、job_id、工资,要求job_id=① and salary>②*/
    SELECT
      a.last_name 姓名,
      a.job_id,
      a.salary    工资
    FROM employees a
    WHERE a.job_id = (SELECT job_id
                          FROM employees
                          WHERE employee_id = 141)
            AND
            a.salary > (SELECT salary
                          FROM employees
                          WHERE employee_id = 143);
  

    Subqueries + group functions, example: Query No. 50 is greater than the minimum wage sector minimum wage and the minimum wage department id [having]

    /*③在②的基础上筛选,满足min(salary)>①*/
    SELECT
      min(a.salary) minsalary,
      department_id
    FROM employees a
    GROUP BY a.department_id
    HAVING min(a.salary) > (SELECT min(salary)
                                FROM employees
                                WHERE department_id = 50);
    

    Error scalar query Example: the above example the query statement ③ neutron min (salary) to the salary, perform the following effects:

    SELECT
            min(a.salary) minsalary,
            department_id
          FROM employees a
          GROUP BY a.department_id
          HAVING min(a.salary) > (SELECT salary
                                      FROM employees
                                      WHERE department_id = 500000);
  ERROR 1242 (21000): Subquery returns more than 1 row
  

  Error: The results of the sub-query returns more than 100 rows.

  Note: The above sub-queries only support up to a row of record .  

  Liezi inquiry  

  Liezi query needs with multi-line operators to use: in (not in), any / some, all.

  To improve efficiency, it is best to re-look distinct keywords.    

  Example 1: Return location_id all employee names department in 1400 or 1700

  / * Return location_id all employee names departments 1400 or 1700 in the * /
  / * mode 1 * /
  / * ① query location_id 1400 or 1700 department number * /
  the SELECT DISTINCT department_id
  the FROM the Departments
  the WHERE location_id  the IN  ( 1400,  1700) ;

  / * ② query employee name, department requested ① is a list of certain * /
  the SELECT a.last_name
  the FROM the employees a
  the WHERE a. department_id  the iN  (the SELECT DISTINCT department_id
                                  the FROM the departments
                                  the WHERE location_id the iN ( 1400,  1700));

  / * mode 2: implemented using any * /
  the SELECT a.last_name
  the FROM A the Employees
  the WHERE a.department_id the aNY = (SELECT DISTINCT department_id
                                      FROM departments
                                      WHERE location_id IN (1400, 1700));

  /*拓展,下面与not in等价*/
  SELECT a.last_name
  FROM employees a
  WHERE a.department_id <> ALL (SELECT DISTINCT department_id
                                      FROM departments
                                      WHERE location_id IN (1400, 1700));
  

  Example 2: in return other types of jobs than any job_id low 'IT_PROG' employees' wages the employee number, name, job_id, salary

  / * Return other types of work in the 'IT_PROG' jobs any low-wage employees employees number more than job_id is, name, job_id, salary * /
  / * ① inquiry department of any job_id as 'IT_PROG' - wage * /
    the SELECT DISTINCT salary
    the FROM the Employees
    the WHERE the job_id =  'IT_PROG';

  / * ② query employee number, name, job_id, salary, slary <any of ① a * /
    the SELECT
      last_name,
      the employee_id,
      the job_id,
      the salary
    the FROM the employees
    the WHERE the salary <the aNY (the SELECT the DISTINCT the salary
                              the FROM the employees
                              the WHERE the job_id =  'IT_PROG') = the job_id the AND!  'IT_PROG';

  / * or * /
    the SELECT
      last_name,
      the employee_id,
      the job_id,
      salary
    FROM employees
    WHERE salary < (SELECT max(salary)
                        FROM employees
                        WHERE job_id = 'IT_PROG') AND job_id != 'IT_PROG';
  

  Example 3: Return to other types of work than job_id 'IT_PROG' low-wage employees in all departments of the employee number, name, job_id, salary

  / * Return other types than job_id is low 'IT_PROG' department of all employees' wages the employee number, name, job_id, salary * /
    the SELECT
      last_name,
      employee_id,
      job_id,
      salary
    the FROM the Employees
    the WHERE salary <ALL (the SELECT DISTINCT salary
                              the FROM the Employees
                              the WHERE = the job_id  'IT_PROG') = the job_id the AND!  'IT_PROG';

  / * or * /
    the SELECT
      last_name,
      the employee_id,
      the job_id,
      the salary
    the FROM the Employees
    the WHERE the salary <( the SELECT  min (the salary)
                        the FROM the Employees
                        the WHERE the job_id = 'IT_PROG') AND job_id != 'IT_PROG';

  Subquery row (row of the result set multi-column)   

    Example: Query a minimum number of employees and the highest paid employee information, in three ways. 
    /*查询员工编号最小并且工资最高的员工信息*/
    /*①查询最小的员工编号*/
    SELECT min(employee_id)
    FROM employees;
    /*②查询最高工资*/
    SELECT max(salary)
    FROM employees;
    /*③方式1:查询员工信息*/
    SELECT *
    FROM employees a
    WHERE a.employee_id = (SELECT min(employee_id)
                       FROM employees)
      AND salary = (SELECT max(salary)
                    FROM employees);

    /*方式2*/
    SELECT *
    FROM employees a
    WHERE (a.employee_id, a.salary) = (SELECT
                                     min(employee_id),
                                     max(salary)
                                   FROM employees);
    /*方式3*/
    SELECT *
    FROM employees a
    WHERE (a.employee_id, a.salary) in (SELECT
                                     min(employee_id),
                                     max(salary)
                                   FROM employees);

  Behind exists (also called correlated subqueries)    

  1. Syntax: exists (Fun query).

  2. exists Results: 0 or 1, the results of the query exists for concentration determination results of the subquery has a value.

  3. In general, the use of sub-query exists, can be used in place of the absolute, it exists with less.

  4. And in front of the queries are different, this first main query is executed, and then the main query results of the query, the query filter according to the sub, sub-queries related to the main fields used in the query, so called correlated subquery.  

  Example 1: A simple example
       SELECT exists(SELECT employee_id
 

              The Employees the FROM
              the WHERE the salary =  300000 )
 the AS 'EXISTS returns 1 or 0';
     

  Example 2: Query department name for all employees

    /*exists入门案例*/
    SELECT exists(SELECT employee_id
              FROM employees
              WHERE salary = 300000) AS 'exists返回1或者0';

    /*查询所有员工部门名*/
    SELECT department_name
    FROM departments a
    WHERE exists(SELECT 1
                     FROM employees b
                     WHERE a.department_id = b.department_id);

    /*使用in实现*/
    SELECT department_name
    FROM departments a
    WHERE a.department_id IN (SELECT department_id
                                    FROM employees);
     

    Example 3: The query does not employees of department

    /*查询没有员工的部门*/
    /*exists实现*/
    SELECT *
    FROM departments a
    WHERE NOT exists(SELECT 1
                           FROM employees b
                           WHERE a.department_id = b.department_id AND b.department_id IS NOT NULL);
    /*in的方式*/
    SELECT *
    FROM departments a
    WHERE a.department_id NOT IN (SELECT department_id
                                          FROM employees b
                                         WHERE b.department_id IS NOT NULL);

Six, NULL pit    

  Example 1: Using a query in a way no staff departments, as follows:

    SELECT *
    FROM departments a
    WHERE a.department_id NOT IN (SELECT department_id
                                          FROM employees b);

    Empty set (0.00 sec)

    In the case where, when the value is NULL subquery column, the result of the query is an outer blank.

    Recommendation: construction of the table, the column does not allow empty.

Seven summary

  1. This article explains common in sub-queries, please be sure to practice

  2. Note that in, any, some, any usage

  3. Field is empty, in the pit there is a query, this should be noted

  4. Recommended that you create table, the column does not allow null

Guess you like

Origin www.cnblogs.com/biao/p/11764833.html