SELECT <列名1,列名2 …>
FROM <表名1> INNER JOIN <表名2> [ ON子句]
<列名1,列名2…>
:需要检索的列名。<表名1><表名2>
:进行内连接的两张表的表名。mysql> SELECT id,name,age,dept_name -> FROM tb_students_info,tb_departments -> WHERE tb_students_info.dept_id=tb_departments.dept_id; +----+--------+------+-----------+ | id | name | age | dept_name | +----+--------+------+-----------+ | 1 | Dany | 25 | Computer | | 2 | Green | 23 | Chinese | | 3 | Henry | 23 | Math | | 4 | Jane | 22 | Computer | | 5 | Jim | 24 | Computer | | 6 | John | 21 | Math | | 7 | Lily | 22 | Computer | | 8 | Susan | 23 | Economy | | 9 | Thomas | 22 | Chinese | | 10 | Tom | 23 | Economy | +----+--------+------+-----------+ 10 rows in set (0.00 sec)在这里,SELECT 语句与前面介绍的最大差别是:SELECT 后面指定的列分别属于两个不同的表,id、name、age 在表 tb_students_info 中,而 dept_name 在表 tb_departments 中,同时 FROM 字句列出了两个表 tb_students_info 和 tb_departments。WHERE 子句在这里作为过滤条件,指明只有两个表中的 dept_id 字段值相等的时候才符合连接查询的条件。
mysql> SELECT id,name,age,dept_name -> FROM tb_students_info INNER JOIN tb_departments -> WHERE tb_students_info.dept_id=tb_departments.dept_id; +----+--------+------+-----------+ | id | name | age | dept_name | +----+--------+------+-----------+ | 1 | Dany | 25 | Computer | | 2 | Green | 23 | Chinese | | 3 | Henry | 23 | Math | | 4 | Jane | 22 | Computer | | 5 | Jim | 24 | Computer | | 6 | John | 21 | Math | | 7 | Lily | 22 | Computer | | 8 | Susan | 23 | Economy | | 9 | Thomas | 22 | Chinese | | 10 | Tom | 23 | Economy | +----+--------+------+-----------+ 10 rows in set (0.00 sec)在这里的查询语句中,两个表之间的关系通过 INNER JOIN 指定。使用这种语法的时候,连接的条件使用 ON 子句给出,而不是 WHERE,ON 和 WHERE 后面指定的条件相同。
本文链接:http://task.lmcjl.com/news/3876.html