A2-02-17.DML-MySQL Self Join

转载自:http://www.mysqltutorial.org/mysql-self-join/

 

MySQL Self Join

 

Summaryin this tutorial, you will learn how to use MySQL self join that joins a table to itself using join statement.

In the previous tutorials, you have learned how to join a table to the other tables using  INNER JOIN,  LEFT JOINor CROSS JOIN clause. However, there is a special case that you need join a table to itself, which is known as self join.

You use the self join when you want to combine rows with other rows in the same table. To perform the self join operation, you must use a table alias to help MySQL distinguish the left table from the right table of the same table in a single query.

MySQL self join examples

Let’s take a look at the employees table in the sample database.

In the employees table, we store not only employees data but also organization structure data. The reportsto column is used to determine the manager id of an employee.

mysql self join employees table

To get the whole organization structure, you can join the employees table to itself using the employeeNumber and reportsTo columns. The employees table has two roles: one is Manager and the other is Direct Reports.

Try It Out

MySQL Selft Join Example

In the above output, you see only employees who have a manager. However, you don’t see the top manager because his name is filtered out due to the INNER JOIN clause. The top manager is the employee who does not have any manager or his manager no is NULL .

Let’s change the INNER JOIN clause to the LEFT JOIN clause in the query above to include the top manager. You also need to use the IFNULL function to display the top manager if the manger’s name is NULL .

Try It Out

MySQL Self Join with LEFT JOIN technique

By using the MySQL self join, you can display a list of customers who locate in the same city by joining the customers table to itself.

Try It Out

MySQL Self Join cutomers located in the same city

We joined the customers table to itself with the following join conditions:

  • c1.city = c2.city to make sure that both customers have the same city
  • c.customerName > c2.customerName to ensure that we don’t get the same customer.

In this tutorial, we have introduced you to MySQL self join that allows you to join a table to itself by using INNER JOIN or LEFT JOIN clauses.

转载于:https://www.cnblogs.com/zhuntidaoren/p/9517692.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值