mysql -u myUser -p
select User, Host from mysql.user;
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
- localhost can be an ip-address bound to the client connecting or the wildcard
%
which means any remote address.
GRANT ALL PRIVILEGES ON myDB . myTable TO 'newuser'@'localhost';
- ALL is a mysql privilege type and is the most permissive. There are less permisive types available.
myDB . myTable
can be substituted for the wildcard*
which matches any.
-- show databases
show databases;o
-- create database
create database myDB;
-- select database
use myDB;
-- delete database
drop database myDB;
use Library;
create table Books
(
id int auto_increment
primary key,
bookName varchar(50) not null
)
collate = utf8mb4_unicode_ci;
-- show columns
describe Books;
-- show tables
show tables;
-- delete tables
drop table Books;
-- single
INSERT INTO Books (id, bookName) VALUES (1, 'How I Play Golf');
-- multiple
INSERT INTO Books (id, bookName) VALUES (1, 'How I Play Golf'), (2, 'Tiger Woods'), (3, 'Tiger Woods');
select * from Books where bookName = 'Tiger Woods';
select * from Books where id between 1 and 2;
delete from Books where id = 1;
update Books
set bookName = 'How I Play Golf - Tiger Woods'
where id = 1;
-- add rating column
alter table Books
add column rating INT;
-- update row
update Books
set rating = 5
where id = 1;
select distinct bookName, rating from Books
order by bookName;
select concat("BookName ", bookName, " rating ", rating) as "Description" from Books;
select distinct bookName, rating from Books;
select bookName, rating
from Books
where bookName like '%Tiger%';
select bookName, rating
from Books
where rating in (4, 5);
-- create an index
create index names
on Books (id, bookName);
-- remove an index
alter table Books
drop index names;
One customer, many transaction logs.
create table Customer
(
id int auto_increment
primary key,
fullName varchar(32) not null
)
collate = utf8mb4_unicode_ci;
create table TransactionLog
(
id int auto_increment
primary key,
customerID int not null,
bookID int not null,
foreign key(customerID) references Customer(id),
foreign key(bookID) references Books(id)
)
collate = utf8mb4_unicode_ci;
Only return customers that have a transaction.
select Customer.fullName, TransactionLog.id
from Customer inner join TransactionLog
on Customer.id = TransactionLog.customerID;
Return transactions and the associated book name
select Customer.fullName, TransactionLog.id, Books.bookName
from Customer inner join TransactionLog
on Customer.id = TransactionLog.customerID
inner join Books on TransactionLog.BookID = Books.id;