Home  >  Article  >  Database  >  mysql advanced (9) multi-table query

mysql advanced (9) multi-table query

黄舟
黄舟Original
2017-02-09 15:32:011038browse

MySQL multi-table query

1 Use the SELECT clause for multi-table query

SELECT field name FROM table 1, table 2... WHERE table 1. field = table 2. field AND others Query conditions

SELECT a.id,a.name,a.address,a.date,b.math,b.english,b.chinese FROM tb_demo065_tel AS b,tb_demo065 AS a WHERE a.id=b.id

Note: In the above code, the association between the two tables is established based on the condition that the id field information of the two tables is the same. However, it should not be used in this way in actual development. It is best to use primary foreign keys. Constraints to achieve

2 Use table aliases for multi-table queries

For example:

SELECT a.id,a.name,a.address,b.math,b.english,b.chinese FROM tb_demo065  a,tb_demo065_tel  b WHERE a.id=b.id 
AND b.id='$_POST[textid]'

In SQL language, you can specify aliases for tables in two ways

The first is to specify it through the keyword AS, such as

SELECT a.id,a.name,a.address,b.math,b.english,b.chinese FROM tb_demo065 AS a,tb_demo065_tel AS b WHERE a.id=b.id

The second is to add the alias of the table directly after the table name to achieve

SELECT a.id,a.name,a.address,b.math,b.english,b.chinese FROM tb_demo065  a,tb_demo065_tel  b WHERE a.id=b.id

Using the table Several points should be noted when using aliases

(1) An alias is usually a shortened table name, used to refer to specific columns in a table in a connection. If there are multiple tables in the connection, Columns with the same name exist, and the column name must be qualified with the table name or table alias

(2) If the table alias is defined, the table name cannot be used again

3 Merge multiple result sets

In SQL language, the query results of multiple SELECT statements can be combined and output through UNION or ALL. The usage instructions of these two keywords are as follows:

UNION: This keyword can be used to combine The query results of multiple SELECT statements are combined and output, and duplicate rows are deleted

ALL: This keyword can be used to combine the query results of multiple SELECT statements and output, but duplicate rows will not be deleted

When using the UNION or ALL keyword to merge multiple tables for output, the query results must have the same structure and the data types must be compatible. In addition, when using UNION, the number of fields in the two tables must also be the same, otherwise an error in the SQL statement will be prompted.

e.x:SELECT id,name,pwd FROM tb_demo067 UNION SELECT  uid,price,date FROM tb_demo067_tel

Four Simple Nested Query

Subquery: A subquery is a SELECT query that returns a single value and is nested in SELECT, INSERT, UPDATE and DELETE statements or other query statements , subqueries can be used anywhere expressions can be used.

SELECT id,name,sex,date FROM tb_demo068 WHERE id in(SELECT id FROM tb_demo068 WHERE id='$_POST[test]')

Inner join: Using the query results as the query condition of the WHERE clause is called an inner join

5 Complex nested queries

Nested queries between multiple tables can be implemented through predicate IN. The syntax format is as follows:

test_expression[NOT] IN{
 subquery
}

Parameter description: test_expression refers to the SQL expression, and subquery contains a certain result set Subquery

The principle of multi-table nested query: no matter how many tables are nested, there must be some kind of correlation between tables. This correlation is established through the WHERE clause to implement the query

6 The application of nested queries in query statistics

When implementing multi-table queries, you can use the predicates ANY, SOME, and ALL at the same time. These predicates are called quantitative comparison predicates and can be combined with comparison operators. Use to determine whether all return values ​​satisfy the search conditions. The SOME and ANY predicates are existential and only focus on whether any return values ​​satisfy the search conditions. These two predicates have the same meaning and can be used interchangeably; the ALL predicate is called a universal predicate. It only cares about whether there is a predicate that meets the search requirements.

SELECT * FROM tb_demo069_people WHERE uid IN(SELECT deptID FROM tb_demo069_dept WHERE deptName='$_POST[select]')
SELECT a.id,a.name FROM tb_demo067 AS a WHERE id<3)

>ANY is greater than a certain value in the subquery

>=ANY is greater than or equal to a value in the subquery A value

1990a48ba9104d54fcdc6f343415d065ANY is not equal to a value in the subquery

>ALL is greater than all values ​​in the subquery

>=ALL is greater than or equal to the value in the subquery All values ​​

624ea91361d164d62f4fcbdf4126b77dALL Not equal to all the values ​​in the subquery

7 Use subquery as a derived table

In the actual project development process, it is often used to derive a table containing only For information tables with several key fields, this goal can be achieved through subqueries, such as

SELECT people.name,people.chinese,people.math,people.english FROM (SELECT name,chinese,math,english FROM tb_demo071) AS people

Note: Subqueries should follow the following rules:

(1)由比较运算符引入的内层子查询只包含一个表达式或列名,在外层语句中的WHERE子句内命名的列必须与内层子查询命名的列兼容

(2)由不可更改的比较运算符引入的子查询(比较运算符后面不跟关键字ANY或ALL)不包括GROUP BY 或 HAVING子句,除非预先确定了成组或单个的值

(3)用EXISTS引入的SELECT列表一般都由*组成,不必指定列名

(4)子查询不能在内部处理其结果

八 使用子查询作表达式

SELECT (SELECT AVG(chinese)FROM tb_demo071),(SELECT AVG(english)FROM tb_demo071),(SELECT AVG(math)FROM tb_demo071) FROM tb_demo071

注:在使用子查询时最好为列表项取个别名,这样可以方便用户在使用mysql_fetch_array()函数时为表项赋值,如

SELECT (SELECT AVG(chinese) FROM tb_demo071) AS yuwen ,(SELECT AVG(english) FROM tb_demo071) 
AS yingyu,(SELECT AVG(math) FROM tb_demo071) AS shuxue FROM tb_demo071

九 使用子查询关联数据

SELECT * FROM tb_demo072_student WHERE id=(SELECT id FROM tb_demo072_class WHERE className = &#39;$_POST[text]&#39;)

十 多表联合查询

利用SQL语句中的UNION,可以将不同表中符合条件的数据信息显示在同一列中。

e.x:SELECT * FROM tb_demo074_student UNION SELECT * FROM tb_demo074_fasten

注:使用UNION时应注意以下两点:

(1)在使用UNION运算符组合的语句中,所有选择列表的表达式数目必须相同,如列名、算术表达式及聚合函数等

(2)在每个查询表中,对应列的数据结构必须一样。

十一 对联合后的结果进行排序

为了UNION的运算兼容,要求所有SELECT语句都不能有ORDER BY语句,但有一种情况例外,那就是在最后一个SELECT语句中放置ORDER BY 子句实现结果的最终排序输出。

e.x:SELECT * FROM tb_demo074_student UNION SELECT * FROM tb_demo074_fasten ORDER BY id

使用UNION条件上相对比较苛刻,所以使用此语句时一定要注意两个表项数目和字段类型是否相同

十二 条件联合语句

SELECT * FROM tb_demo076_BEIJING GROUP BY name HAVING name=&#39;人民邮电出版社&#39; OR name=&#39;机械工业出版社&#39; UNION SELECT * FROM tb_demo076_BEIJING 
GROUP BY name HAVING name <>&#39;人民邮电出版社&#39; AND name <>&#39;机械工业再版社&#39; ORDER BY id

上面语句应用了GROUP BY分组语句和HAVING语句实现条件联合查询。其实现目的是先保证将'人民邮电出版社'和'机械工业出版社'始终位于名单最前列,然后再输出其它的出版社

十三 简单内连接查询

SELECT filedlist FROM table1 [INNER] JOIN table2 ON table1.column1 = table2.column1

其中,filedlist是要显示的字段,INNER表示表之间的连接方式为内连接,table1.column1=table2.column1用于指明两表间的连接条件,如:

SELECT a.name,a.address,a.date,b.chinese,b.math,b.english FROM tb_demo065 AS a INNER JOIN tb_demo065_tel AS b on a.id=b.id

十四 复杂内连接查询

复杂的内连接查询是在基本的内连接查询的基础上再附加一些查询条件,如:

SELECT a.name,a.address,a.date,b.chinese,b.math,b.english FROM tb_demo065 AS a INNER JOIN tb_demo065_tel AS b on a.id=b.id 
WHERE b.id=(SELECT id FROM  tb_demo065 WHERE tb_demo065.name=&#39;$_POST[text]&#39;)

总之,实现表与表之间的关联的本质是两表之间存在共同的数据项或者相同的数据项,通过WHERE 子句或内连接INNER JOIN … ON 语句将两表连接起来,实现查询

十五 使用外连接实现多表联合查询

(1)LEFT OUTER JOIN表示表之间通过左连接方式相互连接,也可简写成LEFT JOIN,它是以左侧的表为基准故称左连接,左侧表中所有信息将被全部输出,而右侧表信息则只会输出符合条件的信息,对不符合条件的信息则返回NULL

e.x:SELECT a.name,a.address,b.math,b.english FROM tb_demo065 AS A LEFT OUTER JOIN tb_demo065_tel AS b ON a.id=b.id

(2)RIGHT OUTER JOIN表示表之间通过右连接方式相互连接,也可简写成RIGHT JOIN,它是以右侧的表为基准故称右连接,右侧表中所有信息将被全部输出,而左侧表信息则只会输出符合条件的信息,对不符合条件的信息则返回NULL

E.X:SELECT a.name,a.address,b.math,b.english FROM tb_demo065 AS A RIGHT OUTER JOIN tb_demo065_tel AS b ON a.id=b.id

十六 利用IN或NOTIN关键字限定范围

e.x:SELECT * FROM tb_demo083 WHERE code IN(SELECT code FROM tb_demo083 WHERE code BETWEEN &#39;$_POST[text1]&#39; AND &#39;$_POST[text2]&#39;)

利用IN可指定在范围内查询,若要求在某范围外查询可以用NOT IN代替它

十七 由IN引入的关联子查询

e.x:SELECT * FROM tb_demo083 WHERE code IN(SELECT code FROM tb_demo083 WHERE code = &#39;$_POST[text]&#39;)

十八 利用HAVING语句过滤分组数据

HAVING子句用于指定组或聚合的搜索条件,HAVING通常与GROUP BY 语句一起使用,如果SQL语句中不含GROUP BY子句,则HAVING的行为与WHERE子句一样.

e.x:SELECT name,math FROM tb_demo083 GROUP BY id HAVING math > &#39;95&#39;


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn