①MySQLの構文を打つ時にコメントアウトする方法
⑴「--」
-- select * from products;
⑵「/* */」これは複数の構文を一気にコメントアウトも可能。
/* select * from products; */
②whereを使う
whereは抽出したい条件を指定する時に使う。
下記の場合は、priceが9800円以上のもののみが表示される
select name,price from products where price >= 9800;
idが1の行を取得したいとき
select * from products where id=1;
idが1か2か3の行を取得したいとき
select * from products where id in(1,2,3);
idが1か2か3ではない行を取得したいとき
select * from products where id not in(1,2,3);
名前が「商品0003」の行を取得したいとき
select * from products where name='商品0003';
priceが100でない行を取得
select * from products where price <> 100;
もしくは
select * from products where price != 100;
priceがnullでない行を取得
select * from products where price is not null;
priceがnullである行を取得
select * from products where price is null;
priceが1000から1900である行を取得
select * from products where price between 1000 and 1900;
論理積
betweenを使わなくても取得できる。
select * from products where price >= 1000 and price <= 1900;
論理和
orを使ってどちらかがtrueなら結果を表示する。
select * from products where price = 1000 or price = 2000;
③フィールド名を変える
もともとデータがあると仮定して。例えば、nameとpriceがある。
この二つの表氏名を変更したい場合はasを使う。
select name as 名前,price as 価格 from products;
④もともとあるデータに変更を加える。
priceのデータを税込価格で表示したい場合
select name as 名前,price as 価格,price * 1.08 as 税込価格 from products;
⑤パターンマッチング
likeを使って、そして「%」か「_」を使う
下記の場合は「中」から始まるuserを取得している
select * from users where last_name like '中%';
「中」を含む人を取得したい場合
select * from users where last_name like '%中%';
名前が子で終わるuserを取得したい場合
select * from users where first_name like '%子';
名前が3文字で最後が子で終わるuserを取得したい場合
下記の場合は「_」を2つ書いている
select * from users where first_name like '__子';
⑥limitを使って取得数を制限する
下記は0番目から10番目までのproductsのデータを取得している
select * from products limit 10;
10番目から10個取得したい場合
初めの数字が何番目から取得するかで次の数字は何個まで取得するかである。
実際PCは0から数えるので今回だと11番目のところから始まる。
select * from products limit 10, 10;
記述順序がある(必ずこの順序で書く必要がある)
1, select(取得行(カラム)の指定)
2, from (対象テーブルの指定)
3, where (絞り込み条件の指定)
4, group by (グループ化の条件を指定)
5, having (グループ化した後の絞り込み条件を指定)
6, order by (並び替え条件の指定)
7, limit (取得する行数の制限)
⑦新しくデータベースを作成する方法
create database データベース名;
データベース一覧を見る方法
show database
データベースにテーブルを追加する方法
use データベース名
create table books(id int not null auto_increment primary key, title varchar(255) not null)
intは整数という意味です。
not null はnullを許可しないという意味です。
primary keyはこのidが主キーという意味です。
titleのvarchar(255)は255文字までという意味です。
下記でテーブルが存在するか確認できる。
show テーブル名(今回はbooks);
下記でテーブルの構造が確認できる
show columns from テーブル名(今回はbooks);
列を追加したい場合(今回だとidのあとに追加できる)
alter table テーブル名(今回はbooks)add price int after id;
列名を変更したい場合(今回はpriceという列名を変更する)
alter table テーブル名(今回はbooks)change price unit_price int;
列の削除
alter table テーブル名(今回はbooks)drop unit_price;
テーブルの削除
drop table テーブル名(今回はbooks);
データベースの削除(今回のデータベース名はbook_storeにする)
drop database book_store;