🏷️Mysql

The Basics

Installation
sudo apt install mysql-server -y

Connection

Local mysql
sudo mysql -u student -p
Remote mysql connection
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
  1. find bind-address

  2. change to bind-address = 0.0.0.0

sudo systemctl restart mysql

Common sql

User

Db name is learn, and user is student with password STUDENT

CREATE DATABASE learn CHARACTER SET utf8;
CREATE USER 'student'@'%' IDENTIFIED BY 'STUDENT';
GRANT ALL PRIVILEGES ON learn.* TO 'student'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;

Check users and change passwords

SELECT USER(), CURRENT_USER();
SET PASSWORD FOR 'student'@'%' = 'newpassword';
FLUSH PRIVILEGES;
Tables
Foreign key

Joins

Joins
Multiple Joins
Filtering aggregated data with Joins

Indexing

  • Indexing can speed up your query when you have many records into your db.

  • If you use where user_id = 1729, you can add index for user_id.

  • If you use published_at BETWEEN '2020-01-01 00:00:00' AND '2022-01-01 00:00:00', you can add index to published_at for reduce a query.

Last updated