Mysql Code

2 minute read

Published:

Enter to db host

mysql -hmssv08 -ucptmain -pcpt123
use CPTMAIN

Create table

CREATE TABLE check_alert (
    ID int NOT NULL AUTO_INCREMENT,
    CHECK_TIME DATETIME, 
    TYPE VARCHAR(20), 
    STATIONCODE VARCHAR(20), 
    OBS_TIME DATETIME,
    ELEMENT VARCHAR(50),
    GRADE int, 
    PRIMARY KEY (ID)
    )
    CHARACTER SET utf8;

add index

ALTER TABLE CPTMAIN.GTS_WARNING ADD INDEX `DATETIME_INDEX` (`DATETIME`);

Add column

ALTER TABLE MSGboard ADD COLUMN GenSMS INT(11) NOT NULL DEFAULT 0 AFTER OBS_TIME;

Modife column

ALTER TABLE check_alert MODIFY COLUMN UNIT VARCHAR(20) NOT NULL DEFAULT ''  AFTER THRESHOLD_VALUE;

Drop column

ALTER TABLE check_alert DROP COLUMN FIRST_FOUND;

Copy structre from old table to new table

CREATE TABLE check_alert_test  LIKE check_alert;

Copy structure and data from old to new

ref: link

CREATE TABLE newtable LIKE oldtable; 
INSERT newtable SELECT * FROM oldtable;
-- or 
CREATE TABLE tbl_new AS SELECT * FROM tbl_old;

Update Data

UPDATE check_alert SET THRESHOLD_VALUE= NULL where id=99;

remove UNQIUE constraint

link

SHOW INDEX FROM tbl_name
-- then
ALTER TABLE tbl_name DROP INDEX index_name

Time Zone

select * from table_name where Time>=  DATE_SUB(CONVERT_TZ(Now(),'+00:00','+8:00'), INTERVAL 3 DAY) AND Time <= CONVERT_TZ(Now(),'+00:00','+8:00')

Select command

Not in array

SELECT * FROM albums WHERE name NOT IN ('Wall', 'Profile', 'Cover', 'Instagram')

Like

  1. %: unknown lengths of unknown characters. If searching aXXXX
    SELECT * FROM albums WHERE CustomerName LIKE 'a%'
    
  2. “_” : one unknown character. If searching “aXbXXX”
    SELECT * FROM albums WHERE CustomerName LIKE 'a_b___'
    

Time range

SELECT DATE_SUB("2017-06-15 09:34:21", INTERVAL 15 MINUTE);
SELECT DATE_SUB("2017-06-15 09:34:21", INTERVAL 3 HOUR);
SELECT DATE_SUB("2017-06-15", INTERVAL -2 MONTH);

Insert Data

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

Update Data

UPDATE Customers SET ContactName='Juan' WHERE Country='Mexico';

Null Value

SELECT column_names FROM table_name WHERE column_name IS NULL;
SELECT column_names FROM table_name WHERE column_name IS NOT NULL;

Unique Value

SELECT DISTINCT Country FROM Customers;

Rename Column Name

SELECT CustomerID AS ID, CustomerName AS Customer FROM Customers;