forked from ziad-saab/reddit-nodejs-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreddit.sql
More file actions
100 lines (79 loc) · 2.7 KB
/
reddit.sql
File metadata and controls
100 lines (79 loc) · 2.7 KB
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
-- This creates the users table. The username field is constrained to unique
-- values only, by using a UNIQUE KEY on that column
CREATE TABLE `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL,
`password` VARCHAR(60) NOT NULL,
`createdAt` DATETIME NOT NULL,
`updatedAt` DATETIME NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
);
-- This creates the posts table. The userId column references the id column of
-- users. If a user is deleted, the corresponding posts' userIds will be set NULL.
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(300) DEFAULT NULL,
`url` varchar(2000) DEFAULT NULL,
`userId` int(11) DEFAULT NULL,
`subredditId` int(11) -- this was added!
`createdAt` DATETIME NOT NULL,
`updatedAt` DATETIME NOT NULL,
PRIMARY KEY (`id`),
KEY `userId` (`userId`),
CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE SET NULL
);
-- Access getAllPosts
SELECT *
FROM posts
JOIN users ON (users.id = posts.userId)
JOIN subreddit ON (subreddit.id = posts.subredditId);
-- Get all post for user by User ID
SELECT *
FROM posts
JOIN users
ON (users.id = posts.userId) where userId=?:
-- Get Single post with post ID
SELECT id,title,url,userId, createdAt, updatedAt
FROM posts
WHERE posts.id = ?
-- Get subreddit
CREATE TABLE `subreddit` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30), -- ALTER TABLE subreddit Alter COLUMN name VARCHAR(30) not null
`description` varchar(200),
`createdAt` DATETIME NOT NULL,
`updatedAt` DATETIME NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
);
-- Add subredditId to posts
-- alter post table to add foreign key to subreddit
alter Table posts add subredditId int(11)
ALTER TABLE `posts` ADD
FOREIGN KEY (`subredditId` )
REFERENCES `subreddit` (`id` ) ON DELETE SET NULL;
-- Get all subreddits
SELECT *
FROM subreddit
ORDER BY createdAt
DESC
-- making alias for getAllPosts'
SELECT p.id as postId,
p.title, p.url,
p.createdAt as postCreatedAt,
p.updatedAt as postUpdatedAt,
u.id as usernameId,
u.username,
u.createdAt as userCreatedAt,
u.updatedAt as userUpdatedAt,
s.id as subredditId,
s.name as subredditName,
s.description as subredditDescription,
s.createdAt as subredditCreatedAt,
s.updatedAt as subredditUpdatedAt
FROM posts as p
JOIN users as u ON u.id = p.userId
JOIN subreddit as s ON s.id = p.subredditId
GROUP BY postId
ORDER BY postCreatedAt DESC;