join_self.md 1.7 KB
Newer Older
M
join  
Mars Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 自连接

现有 node 表如下:

```mysql
create table node(
    id int primary key auto_increment,
    pid int,
    content varchar(256)
)
```

现在Joe 想要给出 content 以 `fork-` 开头的所有节点,和它们的子节点,输出 `parent_id, parent_content, child_id, child_content`
他应该怎么做?

M
Mars Liu 已提交
16 17
<hr/>

F
feilong 已提交
18
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill){target="_blank"}。
F
feilong 已提交
19

F
feilong 已提交
20 21
* `show databases;` 列出所有数据库
* `show tables;` 列出所有表
M
Mars Liu 已提交
22

M
join  
Mars Liu 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
## 答案

```mysql
select l.id as parent_id, 
       l.content as parent_content,
       r.id as child_id,
       r.content as child_content
from node as l
    join node as r on l.id = r.pid
where l.content like 'fork-%';
```

## 选项

### A

```mysql
select l.id as parent_id, 
       l.content as parent_content,
       r.id as child_id,
       r.content as child_content
from node as l
    right join node as r on l.id = r.pid
where l.content like 'fork-%';
```

### B

```mysql
select l.id as parent_id, 
       l.content as parent_content,
       r.id as child_id,
       r.content as child_content
from node as l,  node as r 
where l.id =(+) r.pid l.content like 'fork-%';
```

### C

```mysql
select l.id as parent_id, 
       l.content as parent_content,
       r.id as child_id,
       r.content as child_content
from node as l
    cross join node as r on l.id = r.pid
where l.content like 'fork-%';
```

### D

```mysql
select l.id as parent_id, 
       l.content as parent_content,
       r.id as child_id,
       r.content as child_content
from node as l
    join node as r on l.pid = r.id
where l.content like 'fork-%';
```