自连接是连接的一种用法,但并不是连接的一种类型,因为他的本质是把一张表当成两张表来使用。
mysql有时在信息查询时需要进行对自身连接(自连接),所以我们需要为表定义别名。
-- 创建表 CREATE TABLE products ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(20), price DOUBLE(6,2) ); -- 添加数据 INSERT INTO products(name,price) VALUES ('苹果',12), ('香蕉',15), ('梨子',13), ('桃子',14), ('橘子',11);
-- 获取可重排列 有相同元素构成的对 SELECT p1.name AS name1 ,p2.name AS name2 FROM products p1,products p2; -- 也可写为 SELECT p1.name as name1,p2.name as namem2 FROM products p1 JOIN products p2; -- 执行结果里每一行(记录)都是一个有序对。因为是可重排列,所以结果行数为 5^2 = 25 条数据 -- 可排除掉由相同元素构成的对 SELECT p1.name as name1 ,p2.name as name2 FROM products p1,products p2 WHERE p1.name <> p2.name; -- 元素顺序的对进行去重 SELECT p1.name as name1 ,p2.name as name2 FROM products p1,products p2 WHERE p1.name < p2.name; -- 组合 SELECT p1.name as name1,p2.name as name2,p3.name as name3,p4.name as name4,p5.name as name5 FROM products p1,products p2,products p3,products p4,products p5 WHERE p1.name > p2.name and p2.name > p3.name and p3.name > p4.name and p4.name > p5.name