-
Notifications
You must be signed in to change notification settings - Fork 425
/
Copy pathsql.recursive.html
229 lines (206 loc) · 13 KB
/
sql.recursive.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>7.3. 递归查询</title><link rel="stylesheet" type="text/css" href="/docbook.css" /><meta name="generator" content="DocBook XSL Stylesheets V1.79.1" /><link rel="home" href="index.html" title="Netkiller PostgreSQL 手札" /><link rel="up" href="sql.html" title="第 7 章 SQL" /><link rel="prev" href="orderby.html" title="7.2. ORDER BY 排序" /><link rel="next" href="returning.html" title="7.4. returning" /></head><body><a xmlns="" href="//www.netkiller.cn/">Home</a> |
<a xmlns="" href="//netkiller.github.io/">简体中文</a> |
<a xmlns="" href="http://netkiller.sourceforge.net/">繁体中文</a> |
<a xmlns="" href="/journal/index.html">杂文</a> |
<a xmlns="" href="//www.netkiller.cn/home/donations.html">打赏(Donations)</a> |
<a xmlns="" href="https://github.com/netkiller">Github</a> |
<a xmlns="" href="http://my.oschina.net/neochen/">OSChina 博客</a> |
<a xmlns="" href="https://cloud.tencent.com/developer/column/2078">云社区</a> |
<a xmlns="" href="https://yq.aliyun.com/u/netkiller/">云栖社区</a> |
<a xmlns="" href="https://www.facebook.com/bg7nyt">Facebook</a> |
<a xmlns="" href="http://cn.linkedin.com/in/netkiller/">Linkedin</a> |
<a xmlns="" href="https://zhuanlan.zhihu.com/netkiller">知乎专栏</a> |
<a xmlns="" href="//www.netkiller.cn/home/video.html">视频教程</a> |
<a xmlns="" href="//www.netkiller.cn/home/about.html">About</a><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">7.3. 递归查询</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="orderby.html">上一页</a> </td><th width="60%" align="center">第 7 章 SQL</th><td width="20%" align="right"> <a accesskey="n" href="returning.html">下一页</a></td></tr></table><hr /></div><table xmlns=""><tr><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&repo=netkiller.github.io&type=watch&count=true&size=large" height="30" width="170" frameborder="0" scrolling="0" style="width:170px; height: 30px;" allowTransparency="true"></iframe></td><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&repo=netkiller.github.io&type=fork&count=true&size=large" height="30" width="170" frameborder="0" scrolling="0" style="width:170px; height: 30px;" allowTransparency="true"></iframe></td><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&type=follow&count=true&size=large" height="30" width="240" frameborder="0" scrolling="0" style="width:240px; height: 30px;" allowTransparency="true"></iframe></td></tr></table><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="sql.recursive"></a>7.3. 递归查询</h2></div></div></div>
<p>http://old.storytotell.org/blog/2009/08/11/postgresql84-recursive-queries.html</p>
<div class="example"><a id="idp62"></a><p class="title"><strong>例 7.1. 递归查询实例</strong></p><div class="example-contents">
<p>http://justcramer.com/2010/05/30/scaling-threaded-comments-on-django-at-disqus/</p>
<pre class="screen">
create table comments (
id SERIAL PRIMARY KEY,
message VARCHAR,
author VARCHAR,
parent_id INTEGER REFERENCES comments(id)
);
insert into comments (message, author, parent_id)
values ('This thread is really cool!', 'David', NULL), ('Ya David, we love it!', 'Jason', 1), ('I agree David!', 'Daniel', 1), ('gift Jason', 'Anton', 2),
('Very interesting post!', 'thedz', NULL), ('You sir, are wrong', 'Chris', 5), ('Agreed', 'G', 5), ('Fo sho, Yall', 'Mac', 5);
</pre>
<pre class="screen">
WITH RECURSIVE cte (id, message, author, path, parent_id, depth) AS (
SELECT id,
message,
author,
array[id] AS path,
parent_id,
1 AS depth
FROM comments
WHERE parent_id IS NULL
UNION ALL
SELECT comments.id,
comments.message,
comments.author,
cte.path || comments.id,
comments.parent_id,
cte.depth + 1 AS depth
FROM comments
JOIN cte ON comments.parent_id = cte.id
)
SELECT id, message, author, path, depth FROM cte ORDER BY path;
</pre>
<p>输出结果</p>
<pre class="screen">
id | message | author | path | depth
----+-----------------------------+--------+---------+-------
1 | This thread is really cool! | David | {1} | 1
2 | Ya David, we love it! | Jason | {1,2} | 2
4 | gift Jason | Anton | {1,2,4} | 3
3 | I agree David! | Daniel | {1,3} | 2
5 | Very interesting post! | thedz | {5} | 1
6 | You sir, are wrong | Chris | {5,6} | 2
7 | Agreed | G | {5,7} | 2
8 | Fo sho, Yall | Mac | {5,8} | 2
(8 rows)
</pre>
</div></div><br class="example-break" />
<div class="example"><a id="idp63"></a><p class="title"><strong>例 7.2. 递归查询实例 city 表</strong></p><div class="example-contents">
<p>定义结构</p>
<pre class="screen">
CREATE TABLE city
(
id serial NOT NULL,
name character varying,
parent_id integer,
status boolean,
CONSTRAINT city_pkey PRIMARY KEY (id),
CONSTRAINT city_parent_id_fkey FOREIGN KEY (parent_id)
REFERENCES city (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE city
OWNER TO sys;
</pre>
<p>插入数据</p>
<pre class="screen">
INSERT INTO city (id, name, parent_id, status) VALUES (1, '广东', NULL, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (2, '湖南', NULL, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (3, '深圳', 1, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (4, '东莞', 1, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (5, '福田', 3, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (6, '南山', 3, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (7, '宝安', 3, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (8, '西乡', 7, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (9, '福永', 7, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (10, '龙华', 7, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (11, '长沙', 2, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (12, '湘潭', 2, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (13, '常德', 2, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (14, '桃源', 13, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (15, '汉寿', 13, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (16, '黑龙江', NULL, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (17, '伊春', 16, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (18, '哈尔滨', 16, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (19, '齐齐哈尔', 16, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (20, '牡丹江', 16, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (21, '佳木斯', 16, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (22, '民治', 10, NULL);
INSERT INTO city (id, name, parent_id, status) VALUES (23, '上塘', 10, NULL);
</pre>
<p>查询</p>
<pre class="screen">
WITH RECURSIVE path(id, name, path, idpath, parent_id, status) AS (
SELECT id, name, '/' || name , '/' || id , parent_id, status FROM city WHERE parent_id is null
UNION
SELECT
city.id,
city.name,
parentpath.path ||
CASE parentpath.path
WHEN '/' THEN ''
ELSE '/'
END || city.name,
parentpath.idpath ||
CASE parentpath.idpath
WHEN '/' THEN ''
ELSE '/'
END || city.id,
city.parent_id, city.status
FROM city, path as parentpath
WHERE city.parent_id = parentpath.id
)
SELECT * FROM path;
</pre>
<p>结果输出</p>
<pre class="screen">
id | name | path | idpath | parent_id | status
----+----------+---------------------------+--------------+-----------+--------
1 | 广东 | /广东 | /1 | |
2 | 湖南 | /湖南 | /2 | |
16 | 黑龙江 | /黑龙江 | /16 | |
3 | 深圳 | /广东/深圳 | /1/3 | 1 |
4 | 东莞 | /广东/东莞 | /1/4 | 1 |
11 | 长沙 | /湖南/长沙 | /2/11 | 2 |
12 | 湘潭 | /湖南/湘潭 | /2/12 | 2 |
13 | 常德 | /湖南/常德 | /2/13 | 2 |
17 | 伊春 | /黑龙江/伊春 | /16/17 | 16 |
18 | 哈尔滨 | /黑龙江/哈尔滨 | /16/18 | 16 |
19 | 齐齐哈尔 | /黑龙江/齐齐哈尔 | /16/19 | 16 |
20 | 牡丹江 | /黑龙江/牡丹江 | /16/20 | 16 |
21 | 佳木斯 | /黑龙江/佳木斯 | /16/21 | 16 |
5 | 福田 | /广东/深圳/福田 | /1/3/5 | 3 |
6 | 南山 | /广东/深圳/南山 | /1/3/6 | 3 |
7 | 宝安 | /广东/深圳/宝安 | /1/3/7 | 3 |
14 | 桃源 | /湖南/常德/桃源 | /2/13/14 | 13 |
15 | 汉寿 | /湖南/常德/汉寿 | /2/13/15 | 13 |
8 | 西乡 | /广东/深圳/宝安/西乡 | /1/3/7/8 | 7 |
9 | 福永 | /广东/深圳/宝安/福永 | /1/3/7/9 | 7 |
10 | 龙华 | /广东/深圳/宝安/龙华 | /1/3/7/10 | 7 |
22 | 民治 | /广东/深圳/宝安/龙华/民治 | /1/3/7/10/22 | 10 |
23 | 上塘 | /广东/深圳/宝安/龙华/上塘 | /1/3/7/10/23 | 10 |
(23 rows)
</pre>
</div></div><br class="example-break" />
</div><div xmlns="" id="disqus_thread"></div><script xmlns="">
var disqus_config = function () {
this.page.url = "http://www.netkiller.cn"; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = 'netkiller'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//netkiller.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script><noscript xmlns="">Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript><br xmlns="" /><script xmlns="" type="text/javascript" id="clustrmaps" src="//cdn.clustrmaps.com/map_v2.js?u=r5HG&d=9mi5r_kkDC8uxG8HuY3p4-2qgeeVypAK9vMD-2P6BYM"></script><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="orderby.html">上一页</a> </td><td width="20%" align="center"><a accesskey="u" href="sql.html">上一级</a></td><td width="40%" align="right"> <a accesskey="n" href="returning.html">下一页</a></td></tr><tr><td width="40%" align="left" valign="top">7.2. ORDER BY 排序 </td><td width="20%" align="center"><a accesskey="h" href="index.html">起始页</a></td><td width="40%" align="right" valign="top"> 7.4. returning</td></tr></table></div><script xmlns="">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-11694057-1', 'auto');
ga('send', 'pageview');
</script><script xmlns="" async="async">
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?93967759a51cda79e49bf4e34d0b0f2c";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script><script xmlns="" async="async">
(function(){
var bp = document.createElement('script');
var curProtocol = window.location.protocol.split(':')[0];
if (curProtocol === 'https') {
bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
}
else {
bp.src = 'http://push.zhanzhang.baidu.com/push.js';
}
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(bp, s);
})();
</script><script xmlns="" type="text/javascript" src="/js/q.js" async="async"></script></body></html>