join_self.md 1.7 KB
Newer Older
M
join  
Mars Liu 已提交
1 2 3 4
# 自连接

现有 node 表如下:

fix bug  
张志晨 已提交
5
```sql
M
join  
Mars Liu 已提交
6 7 8 9 10 11 12 13 14 15
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
## 答案

fix bug  
张志晨 已提交
25
```sql
M
join  
Mars Liu 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38
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

fix bug  
张志晨 已提交
39
```sql
M
join  
Mars Liu 已提交
40 41 42 43 44 45 46 47 48 49 50
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

fix bug  
张志晨 已提交
51
```sql
M
join  
Mars Liu 已提交
52 53 54 55 56 57 58 59 60 61
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

fix bug  
张志晨 已提交
62
```sql
M
join  
Mars Liu 已提交
63 64 65 66 67 68 69 70 71 72 73
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

fix bug  
张志晨 已提交
74
```sql
M
join  
Mars Liu 已提交
75 76 77 78 79 80 81 82
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-%';
```