0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

MySQL 備忘録

Last updated at Posted at 2021-11-23

CREATE DATABASE

DB「database_sample」を作成する例

DROP DATABASE IF EXISTS database_sample;
CREATE DATABASE database_sample COLLATE utf8mb4_ja_0900_as_cs_ks;

CREATE TABLE

TB「housework_history」を作成する例

USE `house_work`;

-- 家事履歴のテーブル
DROP TABLE IF EXISTS `housework_history`;
CREATE TABLE `housework_history` (
  `history_id` int(5) NOT NULL AUTO_INCREMENT,
  `lasttime_worksdate` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `flag_nexttimecomp` BIT(1) default 0,
  `works_id` int(5),
  `user_id` int(5),

  PRIMARY KEY (`history_id`),
  FOREIGN KEY works_id(`works_id`) REFERENCES housework_works(`works_id`),
  FOREIGN KEY user_id(`user_id`) REFERENCES housework_users(`user_id`)
  
) COLLATE utf8mb4_ja_0900_as_cs_ks;

カラムの定義で現時刻をデフォルト設定する

`列名`        型       デフォルト 現時刻,
`lasttime_worksdate` DATETIME DEFAULT CURRENT_TIMESTAMP,

FOREIGN KEY(外部キー制約)とは

 外部キー    インデックス名 列名    参照先     テーブル名      列名
  FOREIGN KEY works_id(`works_id`) REFERENCES housework_works(`works_id`),
  FOREIGN KEY user_id(`user_id`) REFERENCES housework_users(`user_id`)

→データを追加・更新する際、他テーブルの特定の列の値しか指定できないようにするもの。

JOIN

→テーブルどうしを結合する際に使う命令。

SELECT
    A.lasttime_worksdate,
    C.category_name,
    B.housework_name,
    B.interval_day,
    DATE_ADD(A.lasttime_worksdate, INTERVAL(B.interval_day)DAY) AS nexttime_houosework,
    D.user_name
FROM
    housework_history AS A 
    INNER JOIN housework_works AS B 
        ON A.works_id = B.works_id 
    INNER JOIN housework_category AS C 
        ON B.category_id = C.category_id 
    INNER JOIN housework_users AS D 
        ON A.user_id = D.user_id;

外部キーエラー

FOREIGN KEY `category_name`(`category_name`) REFERENCES `housework_category`(`category_name`)
エラー内容 原因 備考
Referencing column and referenced column in foreign key constraint are incompatible FOREIGN KEY側とREFERENCES側の指定したキーの型が違う。 【例】VARCHARとINT
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?