4
4

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 5 years have passed since last update.

8章 selectを攻略する

Posted at

リレーションとは

属性のドメインの直積から、特定のタプルだけを選び出して、構成した集合。

selectをデータを取得する唯一の手段

テーブルのリスト→検索条件→カラムのリストの順番でカラムを決定する。

集約関数

sumとかavg、max、min、countなど。

countは特殊な関数

nullに対して、0を返す。
他のだったらnullを返す。avgとかsumとか。

group by

whereはgroup byの前に評価され、
havingはgroup byの後に評価される。 

having whereの違い

集約関数を使う条件文を使用する場合havingを使用する。
where句の中では集約関数は使えない。

whereの時はエラーが出る。

mysql> select * users where age > count(*);

→ Invalid use of group function

havingだとエラーが出ない。

mysql> select * users having age > count(*);

→ User

id name age
1 sato 23
2 tanaka 31

サブクエリとは

select句を入れ子にして埋め込む「サブクエリ」という。
userテーブル、年齢が、maleテーブルの平均年齢以上のレコードを取得したとする。
簡単ですね、男性の平均年齢以上のUserを取得したいときに、select文を入れ子にして埋め込みます。
入れ子になったクエリをサブクエリと呼びます。

mysql> select * from users where	age > (select avg(*) from males);

(select avg(*) from males) → サブクエリ

結果↓

id name age
1 sato 23
2 tanaka 31
4 john 22
4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?