MySQLのselect文の中で加算や除算などの計算を行うことができます。
たとえば、年齢と体重を足し算(加算)したい場合は以下のようにします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
mysql> SELECT age, weight, age + weight from member; +------+--------+--------------+ | age | weight | age + weight | +------+--------+--------------+ | 30 | 57 | 87 | | 32 | 77 | 109 | | 33 | 52 | 85 | | 31 | 67 | 98 | | 27 | 62 | 89 | | 25 | 63 | 88 | | 26 | 43 | 69 | | 35 | 42 | 77 | | 32 | 41 | 73 | | 31 | 51 | 82 | | 29 | 49 | 78 | | 29 | 48 | 77 | | 22 | 47 | 69 | | 35 | 55 | 90 | +------+--------+--------------+ |
WHERE句の中で使う場合
1 2 3 4 5 6 7 8 |
mysql> SELECT weight, age, weight * age from member where weight * age > 1800; +--------+------+--------------+ | weight | age | weight * age | +--------+------+--------------+ | 77 | 32 | 2464 | | 67 | 31 | 2077 | | 55 | 35 | 1925 | +--------+------+--------------+ |
ORDER BY句の中でも使うことが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
mysql> SELECT weight, age, weight - age from member order by weight - age; +--------+------+--------------+ | weight | age | weight - age | +--------+------+--------------+ | 42 | 35 | 7 | | 41 | 32 | 9 | | 43 | 26 | 17 | | 48 | 29 | 19 | | 52 | 33 | 19 | | 49 | 29 | 20 | | 51 | 31 | 20 | | 55 | 35 | 20 | | 47 | 22 | 25 | | 57 | 30 | 27 | | 62 | 27 | 35 | | 67 | 31 | 36 | | 63 | 25 | 38 | | 77 | 32 | 45 | +--------+------+--------------+ |
演算子の優先順位は “*”, “/” が高く、 “+”, “-” が低くなってます。
優先順位を変えたいときは()を使います。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
mysql> SELECT weight, age, weight * (age - 10) from member; +--------+------+---------------------+ | weight | age | weight * (age - 10) | +--------+------+---------------------+ | 57 | 30 | 1140 | | 77 | 32 | 1694 | | 52 | 33 | 1196 | | 67 | 31 | 1407 | | 62 | 27 | 1054 | | 63 | 25 | 945 | | 43 | 26 | 688 | | 42 | 35 | 1050 | | 41 | 32 | 902 | | 51 | 31 | 1071 | | 49 | 29 | 931 | | 48 | 29 | 912 | | 47 | 22 | 564 | | 55 | 35 | 1375 | +--------+------+---------------------+ |
/