Friday, June 8, 2012

Mysql [ if / else | DATA / TIME ]

Sintaxe : IF(<condition>, <value if true>, <value if false>)



mysql> create table reserva(id int(10) primary key  auto_increment, tempo time, data date);
Query OK, 0 rows affected (0.08 sec)

mysql> desc reserva;
+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| id    | int(10) | NO   | PRI | NULL    | auto_increment |
| tempo | time    | YES  |     | NULL    |                |
| data  | date    | YES  |     | NULL    |                |
+-------+---------+------+-----+---------+----------------+
3 rows in set (0.04 sec)


mysql> insert into reserva (tempo,data) values (CURTIME(),CURDATE());
Query OK, 1 row affected (0.00 sec)

mysql> insert into reserva (tempo,data) values ('10:33:40','2010-06-10');
Query OK, 1 row affected (0.39 sec)

mysql> insert into reserva (tempo,data) values ('05:43:40','2000-03-10');
Query OK, 1 row affected (0.00 sec)


mysql> select curtime();
+-----------+
| curtime() |
+-----------+
| 00:11:42  |
+-----------+
1 row in set (0.03 sec)

mysql> select * from reserva where id = 1 and if(tempo > curtime() , 1 , 0 );
+----+----------+------------+
| id | tempo    | data       |
+----+----------+------------+
|  1 | 17:33:40 | 2012-06-08 |
+----+----------+------------+
1 row in set (0.00 sec)

mysql> select * from reserva where id = 1 and if(tempo > curtime() , 0 , 1 );
Empty set (0.00 sec)

mysql> select CURDATE();
+------------+
| CURDATE()  |
+------------+
| 2012-06-09 |
+------------+
1 row in set (0.00 sec)

mysql> select * from reserva where id = 1 and if(data < curdate() , 1 , 0 );
+----+----------+------------+
| id | tempo    | data       |
+----+----------+------------+
|  1 | 17:33:40 | 2012-06-08 |
+----+----------+------------+
1 row in set (0.00 sec)

mysql> select * from reserva where id = 1 and if(data < curdate() , 0 , 1 );
Empty set (0.00 sec)

mysql> select * from reserva where id = 1 and if(data > curdate() , 1 , 0 );
Empty set (0.00 sec)

mysql> select * from reserva where id = 1 and if(data > curdate() , 0 , 1 );
+----+----------+------------+
| id | tempo    | data       |
+----+----------+------------+
|  1 | 17:33:40 | 2012-06-08 |
+----+----------+------------+
1 row in set (0.00 sec)



0 comentários:

Post a Comment