March 1st, 2007 by
Liz
my kingdom was lost.
Watch those commas. A little SQL detail that can bite you:
SELECT
SID
NAME,
ETC
FROM MYTABLE
MySQL, and presumably other databases, is just fine with that statement. It’ll alias the field SID to NAME. If you name columns explicitly with the AS keyword, a missing comma will yield an error:
SELECT
SID AS studentid <--baaarf
NAME AS studentname,
ETC AS studentetc
FROM MYTABLE
ˆ Back to top
1 Comment Tags: MySQL, Tips and Tricks :
February 9th, 2007 by
Liz
I fix bugs for a living. I found this doozy recently. Get out your sticky yellow pad and write this down:
Don’t do this:
select now() - max(my_timestamp) from my_table;
Go find a table with a TIMESTAMP field in it.
mysql> select my_timestamp from my_table limit 1;
my_timestamp: 2006-02-15 02:22:15
1 row in set (0.00 sec)
Looks nice. Now try:
mysql> select max(my_timestamp) from my_table;
max(my_timestamp): 2007-01-31 22:39:17
1 row in set (0.35 sec)
Now this:
mysql> select max(my_timestamp)+0 from my_table;
max(my_timestamp)+0: 2007
1 row in set (0.35 sec)
What happened? max(my_timestamp) was evaluated in a numeric context. The timestamp string was truncated at the first non-numeric character.
Something a bit different happens to now:
mysql> select now();
now(): 2007-02-06 22:47:25
1 row in set (0.00 sec)
mysql> select now()+0;
now()+0: 20070206224744
1 row in set (0.00 sec)
So the original exssion now() - max(my_timestamp) will yield
20070206224744 - 2007
which I doubt is what you had in mind.
If you need to calculate the difference in days, try:
to_days(now()) - max(to_days(my_timestamp))
For something a bit more fine-grained, try:
select (unix_timestamp(now())- unix_timestamp(max(stamp)))
ˆ Back to top
No Comments Tags: Database, MySQL :