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.

SQLの超基本メモ

Last updated at Posted at 2021-01-07

(あまり馴染んでいないのでどこか間違えているかもしれない。随時追加。)

ログイン・ログアウト

ssh xxxxxx@www.ooooo       /*サーバーにログイン*/
mysql -u Database_Name -p  /*SQLにログイン*/
quit                       /*SQLからログアウト*/
exit                       /*サーバーからログアウト*/

データベース操作

create database Database_Name;    /*データベースの作成*/
show databases;                   /*データベースの一覧表示*/
use Database_Name;                /*データベースの使用*/
drop database Database_Name;      /*データベースの削除*/

テーブル操作(use宣言したデータベース内での操作)

create table Table_Name (
	Column1_Name int,
	Column2_Name char(1), 
	Column3_Name text
);								/*データベース内にテーブルを作成*/
show tables;                    /*テーブルの一覧表示*/
show columns from Table_Name;   /*テーブルの列の型表示*/
select * from Table_Name;       /*テーブル内の全データを選択・表示(詳述は下)*/
drop table Table_Name;			/*テーブルの削除*/

データ操作

insert into Table_Name values (1,'A', 'Apple');		/*テーブルにデータを追加*/

select * from Table_Name;         					/*テーブル内の全データを選択・表示*/
select Column1_Name, Column2_Name from Table_Name; 	/*列を指定してデータを選択・表示*/
select * from Table_Name where Column1_Name=1;	   	/*条件式を満たす行を指定してデータを選択・表示*/

update Table_Name set Column3_Name='Astronaut' where Column2_Name='A'; /*(selectした範囲内で)データを更新*/
delete from Table_Name where Column1_Name=1;		/*(selectした範囲内で)条件式を満たすデータを削除*/

/*こういうこともできる*/
select Table1.Column3, Table2.Column3 from Table1, Table2
select * from Table1, Table2 
    where Table1.Column1=Table2.Column2 and Table1.Column2=Table2.Column2

その他

つまづいた所メモ

基本はデータベース>テーブル>データの入れ子。

SQLのデータベース名やテーブル名にしばしばつけられている引用符は''ではなく``だが、そもそもあってもなくてもsyntax errorにはならないから個人的には書かない。一方で、insert文にあるように、文字列型の''は当然必要。

SQLはselect以外の方法でデータの中身を見る方法がない(?)か、あまりポピュラーじゃない。
「取得」とか「抽出」という言葉を使うよりも、直訳した「選択」を使った方が語弊がない。
たまに間違えると`>とか->とかになって文から出られなくなる時がある。最悪Control+CでAbortできるが、あまり起こさないように注意。;で終える。

joinを使えばデータの結合がより簡単になるらしい。

SQLの型の例

型名 使用例
固定長文字列型 char(5)
可変長文字列型(()内は最大文字数) varchar(7)
可変長文字列型 text
整数型 int, bigint
浮動小数点型(概数型) real, float, double
固定小数点型(真数型) decimal(5,2),numeric(3,4)

varchar型に文字数オーバーのinsertをすると、Warningが出るだけで文字列の頭だけ入ってしまう。
decimal型とnumeric型は全く同じ。小数を代入する際は(精度(全部の桁数),スケール(小数点以下桁数))を書かなければならない。スケールのデフォルトが0桁なため。

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?