How to query related data in multiple tables at the same time?

In the previous article, we discussed null values ​​in SQL, as well as the problems and solutions that null values ​​may bring.

So far, our queries have been getting data from a single table. At the beginning of this article, we will discuss how to obtain relevant data from multiple tables. Because in relational databases, different information and the connections between them are usually stored in multiple tables. Such as product table, user table, user order table, and related order details table. When we want to view an order, we need to find all the information about the order from these tables at the same time.

In SQL, we can use a multi-table join (JOIN) query to obtain related data in multiple tables.

Connection syntax

During the development of SQL, two syntaxes for join queries appeared:

  • ANSI SQL/86 standard, use FROM and WHERE keywords to specify the connection of the table.
  • ANSI SQL/92 standard, use JOIN and ON keywords to specify the connection of the table;

In the employee table (employee), the employee information and the number of the department are stored; but the department information is stored in the department table (department). If you want to know the name of the employee's department, you need to query both the employee table and the department table. This problem can be solved using FROM and WHERE:

SELECT d.dept_id, e.dept_id, d.dept_name, e.emp_name
  FROM employee e, department d
 WHERE e.dept_id = d.dept_id;

Among them, the comma in the FROM clause is used to connect the two tables; at the same time, the condition for specifying the connection in the WHERE clause is that the department number (e.dept_id) in the employee table is equal to the number (d.dept_id) in the department table. In addition, the alias ࿰

Guess you like

Origin blog.csdn.net/horses/article/details/108729100