-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog_app
92 lines (75 loc) · 2.23 KB
/
blog_app
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
CREATE TABLE IF NOT EXISTS users
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(50),
email VARCHAR(100),
job_title VARCHAR(100),
address VARCHAR(200),
creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP(),
PRIMARY KEY (id)
);
CREATE DATABASE IF NOT EXISTS blog_app;
-- pluralizing the name of the table
USE blog_app;
# Creating a table
DROP TABLE IF EXISTS users;
CREATE TABLE IF NOT EXISTS users
(
# unsigned,NOT SIGNED , no negative values!
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
email VARCHAR(100),
job_title VARCHAR(100),
address VARCHAR(200),
creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP(),
PRIMARY KEY (id)
);
DROP TABLE IF EXISTS posts;
CREATE TABLE IF NOT EXISTS posts
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
title VARCHAR(100),
body TEXT,
PRIMARY KEY (id)
);
DROP TABLE IF EXISTS posts_label;
CREATE TABLE IF NOT EXISTS posts_label
(
post_id INT UNSIGNED NOT NULL, -- relates to table post.id
label_id INT UNSIGNED NOT NULL -- relates to table labels.id
);
DROP TABLE IF EXISTS labels;
CREATE TABLE IF NOT EXISTS labels
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
# only characters 25 max, not to be empty, or null
name CHAR(25) NOT NULL,
primary key (id)
);
INSERT INTO users (name, email, job_title, address)
VALUES ('Dane Miller', '[email protected]', 'Web Developer and Instructor', '1234 my place');
INSERT INTO posts (user_id, title, body)
VALUES (1, 'My first post', 'lots of text and stuff here');
INSERT INTO labels (name)
VALUES ('Awesome');
INSERT INTO labels (name)
VALUES ('The worst');
INSERT INTO labels (name)
VALUES ('Ok');
INSERT INTO posts_label (post_id, label_id)
VALUES (1, 1),
(1, 2),
(1, 3);
SELECT p.id, l.name as label_name
FROM posts p
INNER JOIN posts_label pl ON (pl.post_id = p.id)
INNER JOIN labels l ON (l.id = pl.label_id)
WHERE p.id = 1;
# describing tables
# desc only works in mysql, other sql servers use SHOW
DESC users;
# shows all the tables in a database.
SHOW tables;
# Dropping Tables
DROP TABLE users;