This repository has been archived by the owner on Apr 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
queries.sql
85 lines (82 loc) · 2.57 KB
/
queries.sql
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
--------- example queris that can return tree structures -------------
SELECT
pg_catalog.count(t),
array_to_json(array_agg(row_to_json(t)))::CHARACTER VARYING AS json
FROM (
WITH clients AS (
SELECT clients.id, clients.name FROM clients
)
SELECT
projects.id, projects.name, projects.client_id,
(
SELECT array_to_json(array_agg(row_to_json(tasks)))
FROM (
SELECT tasks.id, tasks.name, tasks.project_id
FROM tasks
WHERE tasks.project_id = projects.id
) tasks
) AS tasks,
(
SELECT array_to_json(array_agg(row_to_json(users)))
FROM (
SELECT users.id, users.name
FROM users, users_projects
WHERE users.id = users_projects.user_id AND projects.id = users_projects.project_id
) users
) AS users,
row_to_json(clients.*) AS client
FROM projects
INNER JOIN clients ON projects.client_id = clients.id
) t;
WITH clients AS (
SELECT clients.id, clients.name FROM clients
)
SELECT
projects.id, projects.name, projects.client_id,
(
SELECT array_to_json(array_agg(row_to_json(tasks)))
FROM (
SELECT tasks.id, tasks.name, tasks.project_id
FROM tasks
WHERE tasks.project_id = projects.id
) tasks
) AS tasks,
(
SELECT array_to_json(array_agg(row_to_json(users)))
FROM (
SELECT users.id, users.name
FROM users
INNER JOIN users_projects ON
users_projects.user_id = users.id AND
users_projects.project_id = projects.id
) users
) AS users,
row_to_json(clients.*) AS client
FROM projects
INNER JOIN clients ON projects.client_id = clients.id
WITH clients AS (
SELECT clients.id, clients.name FROM clients
)
SELECT
projects.id, projects.name, projects.client_id,
(
SELECT array_to_json(array_agg(row_to_json(tasks)))
FROM (
SELECT tasks.id, tasks.name, tasks.project_id
FROM tasks
WHERE tasks.project_id = projects.id
) tasks
) AS tasks,
(
SELECT array_to_json(array_agg(row_to_json(users)))
FROM (
SELECT users.id, users.name
FROM users, users_projects
WHERE
users_projects.user_id = users.id AND
users_projects.project_id = projects.id
) users
) AS users,
row_to_json(clients.*) AS client
FROM projects, clients
WHERE projects.client_id = clients.id