tag:blogger.com,1999:blog-122339132007-02-23T18:56:08.897-08:00MySQL TipsTech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comBlogger34125tag:blogger.com,1999:blog-12233913.post-1116029200319445382005-05-13T17:06:00.000-07:002005-05-13T17:06:40.323-07:00ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a keyIf in Mysql get the message "ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key" when trying to drop a primary key, then do the following:<br /><br />(let's say the table is 'your_table' and the primary key column w/ auto_increment is 'the_column'):<br /><br />alter table your_table change the_column the_column int unsigned;<br /><br />to remove the auto_increment, then do a:<br /><br />alter table your_table drop primary key;Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1114647420409371312005-04-27T17:13:00.000-07:002005-04-27T17:18:09.260-07:00How to show warning messages for LOAD DATA INFILEEver wondered what the warning messages were when you did a load data infile in MySQL? Well in MySQL 4.1.0 and greater you can by issuing a "SHOW WARNINGS" command at the mysql console- e.g.<br /><br />mydb1707>load data infile '/tmp/people.txt'<br /> -> into table webapps.merchants<br /> -> fields terminated by '\t'<br /> -> lines terminated by '\n'<br /> -> ignore 1 lines;<br /><br />Query OK, 103 rows affected, 14 warnings (0.06 sec)<br />Records: 103 Deleted: 0 Skipped: 0 Warnings: 14<br /><br />mydb1707>show warnings;<br />+---------+------+----------------------------------------------+<br />| Level | Code | Message |<br />+---------+------+----------------------------------------------+<br />| Warning | 1265 | Data truncated for column 'state' at row 13 |<br />| Warning | 1265 | Data truncated for column 'phone' at row 13 |<br />| Warning | 1265 | Data truncated for column 'state' at row 14 |<br />| Warning | 1265 | Data truncated for column 'state' at row 52 |<br />| Warning | 1265 | Data truncated for column 'phone' at row 59 |<br />| Warning | 1265 | Data truncated for column 'phone' at row 60 |<br />| Warning | 1265 | Data truncated for column 'phone' at row 61 |<br />| Warning | 1265 | Data truncated for column 'state' at row 71 |<br />| Warning | 1265 | Data truncated for column 'phone' at row 72 |<br />| Warning | 1265 | Data truncated for column 'phone' at row 78 |<br />| Warning | 1265 | Data truncated for column 'phone' at row 82 |<br />| Warning | 1265 | Data truncated for column 'phone' at row 86 |<br />| Warning | 1265 | Data truncated for column 'state' at row 92 |<br />| Warning | 1265 | Data truncated for column 'phone' at row 100 |<br />+---------+------+----------------------------------------------+<br />14 rows in set (0.02 sec)<br /><br /><br />Check out http://dev.mysql.com/doc/mysql/en/show-warnings.html for the full details.Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113736204879732152005-04-17T04:09:00.000-07:002005-04-17T04:10:04.880-07:00MySQL difference between dates in number of daysTo get a date difference in days in Mysql version before 4.1 (where you can use the datediff() function instead), do the following to calculate date difference:<br /><br />select (TO_DAYS(date1)-TO_DAYS(date2))Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113736160017850622005-04-17T04:08:00.001-07:002005-04-17T04:09:20.016-07:00MySQL get last 24 hours example SQLselect count(*) as cnt from log where date >= DATE_SUB(CURDATE(),INTERVAL 1 DAY);Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113736110441966362005-04-17T04:08:00.000-07:002005-04-17T04:08:30.443-07:00Alter table auto_increment examplesALTER TABLE tbl_name AUTO_INCREMENT = 100<br />will start your records at 100<br /><br />ALTER TABLE tbl_name AUTO_INCREMENT = 1000<br />will start your records at 1000Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113735116706426692005-04-17T03:51:00.000-07:002005-04-17T03:51:56.706-07:00Resolving ERROR 1075: Incorrect table definition; There can only be one auto column and it must be defined as a keymysql> alter table test add orig_order int unsigned auto_increment;<br />ERROR 1075: Incorrect table definition; There can only be one auto column and it must be defined as a key<br />mysql> alter table test add orig_order int unsigned auto_increment, add key(orig_order);<br />Query OK, 1221 rows affected (0.10 sec)<br />Records: 1221 Duplicates: 0 Warnings: 0Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113735070895458192005-04-17T03:50:00.000-07:002005-04-17T03:51:10.896-07:00Export a table in mysql to a file in csv format exampleselect * into outfile '/tmp/zips.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'<br />LINES TERMINATED BY '\n'<br />from zips;Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113735010652940062005-04-17T03:49:00.001-07:002005-04-17T03:50:10.653-07:00MySQL find last digit = number example SQLselect address from $db.$table<br />where ascii(right(address, 1)) >= 48 and ascii(right(address, 1)) <= 57Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734978761737042005-04-17T03:49:00.000-07:002005-04-17T03:49:38.760-07:00MySQL find duplicate repords exampleselect address, count(address) as cnt<br />from mailing_list<br />group by address<br />having cnt > 1<br />order by cnt;Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734893408120132005-04-17T03:47:00.000-07:002005-04-17T03:48:13.413-07:00MySQL benchmark (ran 2005-08-17)MySQL Benchmark<br />Hardware: AMD Athlon64 3000+ 512MB software raid-0 on 2 WDD 120 gig HDD (partition RAID)<br />my.cnf as follows:<br /><br />[mysqld]<br />#datadir=/var/lib/mysql<br />#socket=/var/lib/mysql/mysql.sock<br />set-variable = key_buffer_size=32M<br />set-variable = join_buffer_size=32M<br />set-variable = max_allowed_packet=2M<br />set-variable = table_cache=256K<br />set-variable = sort_buffer_size=24M<br />set-variable = net_buffer_length=256K<br />set-variable = myisam_sort_buffer_size=8M<br />set-variable = read_buffer_size=4M<br />set-variable = long_query_time=5<br />set-variable = thread_cache_size=1M<br />set-variable = read_rnd_buffer_size=8M<br />set-variable = tmp_table_size=256M<br />set-variable = record_buffer=1M<br />set-variable = log-slow-queries=/var/log/mysql_slow_queries.log<br />set-variable = long_query_time=3<br />set-variable = query_cache_type=1<br />set-variable = query_cache_size=32M<br />set-variable = query_cache_limit=4M<br />set-variable = max_connections=200<br />skip-innodb<br /><br />[mysql]<br />prompt="\\d\\R\\m>"<br /><br />[mysql.server]<br />user=mysql<br />basedir=/var/lib<br /><br />[safe_mysqld]<br />#err-log=/var/log/mysqld.log<br />#pid-file=/var/run/mysqld/mysqld.pid<br /><br />[root@localhost sql-bench]# perl run-all-tests<br />Benchmark DBD suite: 2.15<br />Date of test: 2004-08-17 14:04:30<br />Running tests on: Linux 2.6.7-1.478 x86_64<br />Arguments:<br />Comments:<br />Limits from:<br />Server version: MySQL 4.1.3 beta standard log<br />Optimization: None<br />Hardware:<br /><br />alter-table:<br />Total time: 20 wallclock secs ( 0.04 usr 0.02 sys + 0.00 cusr 0.00 csys = 0.06 CPU)<br />ATIS: Total time: 6 wallclock secs ( 4.16 usr 0.83 sys + 0.00 cusr 0.00 csys = 4.99 CPU)<br />big-tables: Total time: 7 wallclock secs ( 1.89 usr 1.58 sys + 0.00 cusr 0.00 csys = 3.47 CPU)<br />connect: Total time: 80 wallclock secs (23.86 usr 10.12 sys + 0.00 cusr 0.00 csys = 33.98 CPU)<br />create: Total time: 108 wallclock secs ( 1.21 usr 0.41 sys + 0.00 cusr 0.00 csys = 1.62 CPU)<br />insert:<br /><br />Total time: 1277 wallclock secs (279.28 usr 49.60 sys + 0.00 cusr 0.00 csys = 328.88 CPU)<br />select: Total time: 56 wallclock secs (21.93 usr 3.56 sys + 0.00 cusr 0.00 csys = 25.49 CPU)<br />transactions: Test skipped because the database doesn't support transactions<br />wisconsin: Total time: 4 wallclock secs ( 1.63 usr 0.43 sys + 0.00 cusr 0.00 csys = 2.06 CPU)<br /><br />All 9 test executed successfully<br /><br />Totals per operation:<br />Operation seconds usr sys cpu tests<br />alter_table_add 8.00 0.01 0.00 0.01 100<br />alter_table_drop 9.00 0.02 0.00 0.02 91<br />connect 5.00 2.63 0.52 3.15 10000<br />connect+select_1_row 8.00 3.69 0.75 4.44 10000<br />connect+select_simple 6.00 3.19 0.66 3.85 10000<br />count 7.00 0.03 0.01 0.04 100<br />count_distinct 0.00 0.08 0.01 0.09 1000<br />count_distinct_2 0.00 0.09 0.01 0.10 1000<br />count_distinct_big 5.00 3.75 0.75 4.50 120<br />count_distinct_group 1.00 0.48 0.08 0.56 1000<br />count_distinct_group_on_key 1.00 0.11 0.02 0.13 1000<br />count_distinct_group_on_key_parts 0.00 0.46 0.07 0.53 1000<br />count_distinct_key_prefix 0.00 0.09 0.02 0.11 1000<br />count_group_on_key_parts 0.00 0.45 0.08 0.53 1000<br />count_on_key 12.00 3.95 0.54 4.49 50100<br />create+drop 29.00 0.15 0.03 0.18 10000<br />create_MANY_tables 21.00 0.03 0.00 0.03 10000<br />create_index 2.00 0.00 0.00 0.00 8<br />create_key+drop 31.00 0.18 0.11 0.29 10000<br />create_table 0.00 0.00 0.00 0.00 31<br />delete_all_many_keys 32.00 0.01 0.00 0.01 1<br />delete_big 0.00 0.00 0.00 0.00 1<br />delete_big_many_keys 32.00 0.01 0.00 0.01 128<br />delete_key 1.00 0.15 0.09 0.24 10000<br />delete_range 3.00 0.00 0.00 0.00 12<br />drop_index 1.00 0.00 0.00 0.00 8<br />drop_table 0.00 0.00 0.00 0.00 28<br />drop_table_when_MANY_tables 3.00 0.16 0.09 0.25 10000<br />insert 31.00 5.14 2.84 7.98 350768<br />insert_duplicates 8.00 1.58 0.84 2.42 100000<br />insert_key 39.00 3.00 1.16 4.16 100000<br />insert_many_fields 3.00 0.21 0.06 0.27 2000<br />insert_select_1_key 2.00 0.00 0.00 0.00 1<br />insert_select_2_keys 3.00 0.00 0.00 0.00 1<br />min_max 2.00 0.02 0.00 0.02 60<br />min_max_on_key 17.00 7.10 0.99 8.09 85000<br />multiple_value_insert 2.00 0.20 0.03 0.23 100000<br />once_prepared_select 16.00 3.43 1.38 4.81 100000<br />order_by_big 14.00 10.84 2.38 13.22 10<br />order_by_big_key 16.00 11.15 2.41 13.56 10<br />order_by_big_key2 13.00 10.78 2.39 13.17 10<br />order_by_big_key_desc 16.00 11.22 2.44 13.66 10<br />order_by_big_key_diff 14.00 10.95 2.35 13.30 10<br />order_by_big_key_prefix 14.00 10.86 2.26 13.12 10<br />order_by_key2_diff 2.00 0.97 0.18 1.15 500<br />order_by_key_prefix 1.00 0.53 0.10 0.63 500<br />order_by_range 2.00 0.61 0.09 0.70 500<br />outer_join 1.00 0.00 0.00 0.00 10<br />outer_join_found 1.00 0.00 0.00 0.00 10<br />outer_join_not_found 1.00 0.00 0.00 0.00 500<br />outer_join_on_key 1.00 0.00 0.00 0.00 10<br />prepared_select 24.00 9.12 1.49 10.61 100000<br />select_1_row 10.00 1.78 1.34 3.12 100000<br />select_1_row_cache 4.00 1.36 1.23 2.59 100000<br />select_2_rows 12.00 1.81 1.46 3.27 100000<br />select_big 14.00 10.88 2.34 13.22 80<br />select_big_str 13.00 4.72 0.76 5.48 10000<br />select_cache 1.00 0.76 0.10 0.86 10000<br />select_cache2 27.00 1.85 0.16 2.01 10000<br />select_column+column 12.00 1.76 1.17 2.93 100000<br />select_diff_key 35.00 0.15 0.01 0.16 500<br />select_distinct 1.00 0.80 0.14 0.94 800<br />select_group 2.00 0.52 0.09 0.61 2911<br />select_group_when_MANY_tables 24.00 0.69 0.18 0.87 10000<br />select_join 0.00 0.24 0.04 0.28 100<br />select_key 146.00 27.12 3.51 30.63 200000<br />select_key2 164.00 28.05 3.45 31.50 200000<br />select_key2_return_key 160.00 27.43 3.08 30.51 200000<br />select_key2_return_prim 162.00 27.87 3.18 31.05 200000<br />select_key_prefix 80.00 23.80 3.15 26.95 200000<br />select_key_prefix_join 3.00 2.13 0.42 2.55 100<br />select_key_return_key 154.00 27.36 3.04 30.40 200000<br />select_many_fields 4.00 1.68 1.52 3.20 2000<br />select_range 7.00 4.22 0.85 5.07 410<br />select_range_key2 2.00 1.76 0.30 2.06 25010<br />select_range_prefix 2.00 1.78 0.33 2.11 25010<br />select_simple 5.00 1.53 1.11 2.64 100000<br />select_simple_cache 5.00 1.38 1.12 2.50 100000<br />select_simple_join 0.00 0.28 0.06 0.34 500<br />update_big 11.00 0.00 0.00 0.00 10<br />update_of_key 6.00 0.72 0.43 1.15 50000<br />update_of_key_big 5.00 0.01 0.01 0.02 501<br />update_of_primary_key_many_keys 18.00 0.01 0.01 0.02 256<br />update_with_key 24.00 4.00 2.59 6.59 300000<br />update_with_key_prefix 9.00 2.52 0.95 3.47 100000<br />wisc_benchmark 1.00 1.17 0.17 1.34 114<br />TOTALS 1583.00 329.57 65.53 395.10 3425950Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734819020914312005-04-17T03:46:00.000-07:002005-04-17T03:46:59.020-07:00Created_tmp_tablesThe number of in-memory temporary tables created automatically by the server while executing statements. If Created_tmp_disk_tables is big, you may want to increase the tmp_table_size value to cause temporary tables to be memory-based instead of disk-based.<br /><br />set-variable = tmp_table_size=128MTech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734784148440172005-04-17T03:45:00.000-07:002005-04-17T03:46:24.150-07:00Chang the Mysql client promptChanging the Mysql client prompt: (Mysql 4.0.2 and higher)<br /><br />(from http://dev.mysql.com/doc/mysql/en/mysql_Commands.html)<br /><br />e.g. "prompt \d\R\m>" will show the current database + millitary hour + minutes<br /><br />Put in my.cnf<br /><br />[mysql]<br />prompt="\\d\\R\\m>"Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734710387284822005-04-17T03:44:00.000-07:002005-04-17T03:45:10.386-07:00Faster way of getting random rows in mysql instead of using order by rand()1. create a new indexed column (= column_x) that's integer incremented for each table<br />2. select count(*) to get # of rows<br />3. use the app to generate X # of integers between 1 and last row<br />4. select * from table where column_x in (rand1, rand2, rand3, ...)Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734649690305762005-04-17T03:42:00.000-07:002005-04-17T03:44:09.690-07:00End Query with \G instead of ;You can use \G instead of ; for tables with lots of fields.<br /><br />mysql> SHOW STATUS LIKE 'Qcache%';<br />+-------------------------+-----------+<br />| Variable_name | Value |<br />+-------------------------+-----------+<br />| Qcache_queries_in_cache | 6990 |<br />| Qcache_inserts | 6990 |<br />| Qcache_hits | 3987 |<br />| Qcache_lowmem_prunes | 0 |<br />| Qcache_not_cached | 621 |<br />| Qcache_free_memory | 176329432 |<br />| Qcache_free_blocks | 1 |<br />| Qcache_total_blocks | 13998 |<br />+-------------------------+-----------+<br />8 rows in set (0.00 sec)<br /><br />mysql> SHOW STATUS LIKE 'Qcache%' \G<br />*************************** 1. row ***************************<br />Variable_name: Qcache_queries_in_cache<br /> Value: 7902<br />*************************** 2. row ***************************<br />Variable_name: Qcache_inserts<br /> Value: 7902<br />*************************** 3. row ***************************<br />Variable_name: Qcache_hits<br /> Value: 6456<br />*************************** 4. row ***************************<br />Variable_name: Qcache_lowmem_prunes<br /> Value: 0<br />*************************** 5. row ***************************<br />Variable_name: Qcache_not_cached<br /> Value: 3887<br />*************************** 6. row ***************************<br />Variable_name: Qcache_free_memory<br /> Value: 172986416<br />*************************** 7. row ***************************<br />Variable_name: Qcache_free_blocks<br /> Value: 1<br />*************************** 8. row ***************************<br />Variable_name: Qcache_total_blocks<br /> Value: 15828<br />8 rows in set (0.00 sec)Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734512533717692005-04-17T03:41:00.000-07:002005-04-17T03:41:52.533-07:00Gauging MySQL performance- examplesmysql> show variables like '%query_cache%';<br />+-------------------+-----------+<br />| Variable_name | Value |<br />+-------------------+-----------+<br />| have_query_cache | YES |<br />| query_cache_limit | 4194304 |<br />| query_cache_size | 167772160 |<br />| query_cache_type | ON |<br />+-------------------+-----------+<br />4 rows in set (0.01 sec)<br /><br /><br />mysql> show variables like '%query_cache%';<br />+-------------------+-----------+<br />| Variable_name | Value |<br />+-------------------+-----------+<br />| have_query_cache | YES |<br />| query_cache_limit | 4194304 |<br />| query_cache_size | 167772160 |<br />| query_cache_type | ON |<br />+-------------------+-----------+<br />4 rows in set (0.01 sec)<br /><br />mysql> SHOW STATUS LIKE 'Qcache%';<br />+-------------------------+-----------+<br />| Variable_name | Value |<br />+-------------------------+-----------+<br />| Qcache_queries_in_cache | 2046 |<br />| Qcache_inserts | 2046 |<br />| Qcache_hits | 2385 |<br />| Qcache_lowmem_prunes | 0 |<br />| Qcache_not_cached | 1619 |<br />| Qcache_free_memory | 161661632 |<br />| Qcache_free_blocks | 1 |<br />| Qcache_total_blocks | 4111 |<br />+-------------------------+-----------+<br />8 rows in set (0.00 sec)Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734467031212042005-04-17T03:40:00.000-07:002005-04-17T03:41:07.030-07:00Example my.cnf for 4.0.X[mysqld]<br />datadir=/var/lib/mysql<br />socket=/var/lib/mysql/mysql.sock<br />set-variable = key_buffer_size=160M<br />set-variable = join_buffer_size=64M<br />set-variable = max_allowed_packet=8M<br />set-variable = table_cache=256K<br />set-variable = sort_buffer_size=128M<br />set-variable = net_buffer_length=256K<br />set-variable = myisam_sort_buffer_size=128M<br />set-variable = read_buffer_size=8M<br />set-variable = long_query_time=5<br />set-variable = thread_cache_size=1M<br />set-variable = query_cache_size=8M<br />set-variable = read_rnd_buffer_size=32M<br />set-variable = tmp_table_size=64M<br />set-variable = record_buffer=4M<br />set-variable = log-slow-queries=/var/log/mysql_slow_queries.log<br />set-variable = long_query_time=3<br />set-variable = query_cache_type=1<br />set-variable = query_cache_size=256M<br />set-variable = query_cache_limit=4M<br />skip-innodb<br /><br />[mysql.server]<br />user=mysql<br />basedir=/var/lib<br /><br />[safe_mysqld]<br />err-log=/var/log/mysqld.log<br />pid-file=/var/run/mysqld/mysqld.pidTech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734337828750482005-04-17T03:38:00.000-07:002005-04-17T03:39:56.036-07:00MySQL date calculationse.g. 2 days ago till today:<br /><br />select domain, count(*) as cnt from referrers where date >= current_date()-2 group by domain order by cnt;<br /><br /><br />Simple Date Calculations<br />Date calculations are relatively easy. The first function we're going to look at is the YEAR() function, which returns a year from a given date. For example:<br /><br />mysql> SELECT YEAR('2003-03-31');<br />+--------------------+<br />| YEAR('2003-03-31') |<br />+--------------------+<br />| 2003 |<br />+--------------------+<br /><br />We can perform simple arithmetic on a date using the '+' and '-' operators. For example, to find out which year is five years ahead of a given date, you can use:<br />mysql> SELECT YEAR('2003-03-31')+5;<br />+----------------------+<br />| YEAR('2003-03-31')+5 |<br />+----------------------+<br />| 2008 |<br />+----------------------+<br /><br />And to find out which year was five years in the past:<br />mysql> SELECT YEAR('2003-03-31')-5;<br />+----------------------+<br />| YEAR('2003-03-31')-5 |<br />+----------------------+<br />| 1998 |<br />+----------------------+<br /><br />Of course you don't have to hard-code the date. MySQL is quite capable of telling the date and time, using the NOW() function:<br />mysql> SELECT NOW();<br />+---------------------+<br />| NOW() |<br />+---------------------+<br />| 2003-03-31 00:32:21 |<br />+---------------------+<br /><br />or just the date with the CURRENT_DATE() function:<br />mysql> SELECT CURRENT_DATE();<br />+----------------+<br />| CURRENT_DATE() |<br />+----------------+<br />| 2003-03-31 |<br />+----------------+<br /><br />There are also functions for the other date and time intervals; MONTH(), DAYOFMONTH(), HOUR(), MINUTE() and SECOND(). For example:<br />mysql> SELECT MONTH(NOW()) AS m,<br />DAYOFMONTH(NOW()) AS d,<br />HOUR(NOW()) AS h,<br />MINUTE(NOW()) AS m,<br />SECOND(NOW()) AS s;<br />+------+------+------+------+------+<br />| m | d | h | m | s |<br />+------+------+------+------+------+<br />| 3 | 31 | 1 | 53 | 38 |<br />+------+------+------+------+------+<br /><br />The DAYOFMONTH() function is an exception to the naming conventions because there are a number of other ways to return the day. DAYOFMONTH() returns the day as a numeric from 1 to 31, but there is also DAYNAME() which returns the actual name of the day, DAYOFWEEK() which returns a number from 1 (Sunday) to 7(Saturday) and DAYOFYEAR() returning a number from 1 to 366. Some examples:<br /><br />mysql> SELECT DAYNAME('2000-01-01');<br />+-----------------------+<br />| DAYNAME('2000-01-01') |<br />+-----------------------+<br />| Saturday |<br />+-----------------------+<br /><br />mysql> SELECT DAYOFWEEK('2000-01-01');<br />+-------------------------+<br />| DAYOFWEEK('2000-01-01') |<br />+-------------------------+<br />| 7 |<br />+-------------------------+<br /><br />mysql> SELECT DAYOFYEAR('2000-12-31');<br />+-------------------------+<br />| DAYOFYEAR('2000-12-31') |<br />+-------------------------+<br />| 366 |<br />+-------------------------+<br /><br /><br /><br />One of the most commonly performed date calculations is one which calculates age. Unfortunately there isn't a function to do it, so you need to do a bit of thinking. Let's begin with doing some simple arithmetic - you can see when I'm running these queries from the earlier results (31 March 2003). First, we'll simply subtract the year of birth from the current year. If you're reading this article well after I wrote it, of course your results may be different:<br />mysql> SELECT YEAR(CURRENT_DATE)-YEAR('1971-01-01');<br />+---------------------------------------+<br />| YEAR(CURRENT_DATE)-YEAR('1971-01-01') |<br />+---------------------------------------+<br />| 32 |<br />+---------------------------------------+<br /><br />If you were using this to return the age, the result would be correct. Someone born on the 1st of January 1971 would be 32 years old on the 31st of March 2003. But let's test for someone born on the 31st of December:<br />mysql> SELECT YEAR(CURRENT_DATE)-YEAR('1971-12-31');<br />+---------------------------------------+<br />| YEAR(CURRENT_DATE)-YEAR('1971-12-31') |<br />+---------------------------------------+<br />| 32 |<br />+---------------------------------------+<br /><br />Here the age is wrong. This person would not have turned 32 yet. The problem is that the calculation above only checks the year part of the date. It comes down to subtracting 1971 from 2003, regardless of the month and day. The best way to do this is to compare whether the current month and day are larger than the birth month and day. If it is, a full year has passed, and the year portion of the calculation can be left. If it isn't, a full year hasn't passed, and you need to subtract one from the year portion. It sounds tricky, but it isn't really. Let's break it down slowly. It helps us greatly that MySQL evaluates a true expression to 1, and a false expression to 0. For example:<br />mysql> SELECT 23>19;<br />+-------+<br />| 23>19 |<br />+-------+<br />| 1 |<br />+-------+<br /><br />mysql> SELECT 23<19;> SELECT RIGHT('abcdef',2);<br />+-------------------+<br />| RIGHT('abcdef',2) |<br />+-------------------+<br />| ef |<br />+-------------------+<br /><br />This returns 2 characters, starting from the right of the string, thus 'ef'. If you ask for more characters than the string is long, MySQL simply returns the whole string:<br />mysql> SELECT RIGHT('abcdef',9);<br />+-------------------+<br />| RIGHT('abcdef',9) |<br />+-------------------+<br />| abcdef |<br />+-------------------+<br /><br />So, to return the 'MM-DD' portion of a date, you need to return the five rightmost characters, for example:<br />mysql> SELECT RIGHT(CURRENT_DATE(),5);<br />+-------------------------+<br />| RIGHT(CURRENT_DATE(),5) |<br />+-------------------------+<br />| 03-31 |<br />+-------------------------+<br /><br />Now we have everything we need to calculate an age. The query will have a portion that calculates the difference in years, and then we'll subtract either 0 or 1, depending on the month-day portion. Here is the full query:<br />mysql> SELECT YEAR(CURRENT_DATE()) - YEAR('1971-12-31')<br />- (RIGHT(CURRENT_DATE(),5)<'12-31') AS age;<br />+------+<br />| age |<br />+------+<br />| 31 |<br />+------+Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734279941667082005-04-17T03:37:00.000-07:002005-04-17T03:37:59.943-07:00MySQL Explain exampleEXPLAIN SELECT employee_number,firstname,surname FROM employee WHERE employee_number= '10875';<br /><br /><br />+----------+------+---------------+------+---------+------+------+------------+<br />| table | type | possible_keys | key | key_len | ref | rows | Extra |<br />+----------+------+---------------+------+---------+------+------+------------+<br />| employee | ALL | NULL | NULL | NULL | NULL | 2 | where used |<br />+----------+------+---------------+------+---------+------+------+------------+<br /><br />So what are all these things?<br /><br />-table shows us which table the output is about (for when you join many tables in the query)<br />-type is an important one - it tells us which type of join is being used. From best to worst the types are: system, const, eq_ref, ref, range, index, all<br />-possible_keys Shows which possible indexes apply to this table<br />-key And which one is actually used<br />-key_len give us the length of the key used. The shorter that better.<br />-ref Tells us which column, or a constant, is used<br />-rows Number of rows mysql believes it must examine to get the data<br />extra Extra info - the bad ones to see here are "using temporary" and "using filesort"Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734128592410122005-04-17T03:34:00.000-07:002005-04-17T03:35:28.593-07:00Some built-in MySQL functionsmysql> select version();<br />+---------------+<br />| version() |<br />+---------------+<br />| 3.23.29-gamma |<br />+---------------+<br />1 row in set (0.00 sec)<br /><br />mysql> select database();<br />+------------+<br />| database() |<br />+------------+<br />| main |<br />+------------+<br />1 row in set (0.01 sec)<br /><br />mysql> SELECT PASSWORD("mypass");<br />+--------------------+<br />| PASSWORD("mypass") |<br />+--------------------+<br />| 6f8c114b58f2ce9e |<br />+--------------------+<br />1 row in set (0.01 sec)<br /><br />mysql> select md5('test');<br />+----------------------------------+<br />| md5('test') |<br />+----------------------------------+<br />| 098f6bcd4621d373cade4e832627b4f6 |<br />+----------------------------------+<br />1 row in set (0.02 sec)Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113734015452521902005-04-17T03:33:00.000-07:002005-04-17T03:33:35.453-07:00Problem in Mysql with equality comparison with floatThere is a general problem when testing a floating point field for equality. The test (field=14.40) doesn't work because field is not exactly 14.40, but it could be 13.9999 or 14.0001. Use this test instead: (field between 13.9999 and 14.0001). Moreover, as a general rule, if you want precise results, don't use float, but decimal, and test by ranges (between y and z), instead of exact values (= x).Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113733972878445912005-04-17T03:31:00.000-07:002005-04-17T03:32:52.880-07:00Do a join on the same table in MySQLYou can join the same table in mysql!<br /><br />mysql> select mv2.name, mv1.quantity<br /> -> from dw.MAILVRS mv1, dw.MAILVRS mv2<br /> -> where mv1.version_recnum = 124475 and mv1.package_recnum = mv2.dataflex_recnum_one;<br /><br />+---------+----------+<br />| name | quantity |<br />+---------+----------+<br />| Kit A | 25000 |<br />| Control | 50000 |<br />| Kit E | 25000 |<br />+---------+----------+Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113733902029533502005-04-17T03:29:00.000-07:002005-04-17T03:31:42.030-07:00MySQL outer join SQL tutorial/examplesFirst of all, outer joins are for instances where info is being looked up on another table and you want rows returned even though nothing was matched for a particular id, e.g.:<br /><br />create table food (<br /> id int unsigned primary key auto_increment,<br /> food char(16),<br /> yummy char(1),<br /> animal char(16)<br />);<br /><br />create table animals (<br /> name char(16) primary key,<br /> weight int unsigned<br />);<br /><br />insert into food values<br />(NULL, 'apple', 'Y', 'human'),<br />(NULL, 'oranges', 'Y', 'human'),<br />(NULL, 'apple', 'N', 'dog'),<br />(NULL, 'oranges', 'N', 'dog'),<br />(NULL, 'apple', 'N', 'cat'),<br />(NULL, 'oranges', 'N', 'cat');<br /><br />insert into animals values<br />('cat', 12),<br />('dog', 25);<br /><br />table 'food'<br /><br />id food yummy animal<br />--- ---- ----- ------<br />1 apple Y human<br />2 oranges Y human<br />3 apple N dog<br />4 oranges N dog<br />5 apple N cat<br />6 oranges N cat<br /><br /><br />table 'animals'<br /><br />name weight<br />---- ------<br />Cat 12<br />Dog 25<br /><br />Let's say you want a list of all the foods and the weight of the animals.<br /><br />If you do:<br /><br />select f.*, a.weight<br />from food f, animals a<br />where f.animal = a.name<br /><br />In this case the result would be:<br /><br />+----+---------+-------+--------+--------+<br />| id | food | yummy | animal | weight |<br />+----+---------+-------+--------+--------+<br />| 5 | apple | N | cat | 12 |<br />| 6 | oranges | N | cat | 12 |<br />| 3 | apple | N | dog | 25 |<br />| 4 | oranges | N | dog | 25 |<br />+----+---------+-------+--------+--------+<br /><br /><br />Notice that humans is missing, but if you want the humans to show up even<br />though there's no human entry in the 'animals' table you have to do an<br />outer join (aka LEFT [OUTER] JOIN in Mysql):<br /><br />select f.*, a.weight<br />from food f<br />LEFT JOIN animals a on (f.animal=a.name)<br /><br />In this case the result would be:<br /><br />+----+---------+-------+--------+--------+<br />| id | food | yummy | animal | weight |<br />+----+---------+-------+--------+--------+<br />| 1 | apple | Y | human | NULL |<br />| 2 | oranges | Y | human | NULL |<br />| 3 | apple | N | dog | 25 |<br />| 4 | oranges | N | dog | 25 |<br />| 5 | apple | N | cat | 12 |<br />| 6 | oranges | N | cat | 12 |<br />+----+---------+-------+--------+--------+<br /><br />Here are some more examples:<br /><br />SELECT T.name, V.value, T.unit, T.id, A.Product_id<br />FROM attribute_type AS T<br />LEFT JOIN attribute AS A ON ( T.id = A.type_id AND A.Product_id = 21 )<br />LEFT JOIN attribute_value AS V ON ( A.value_id = V.id );<br /><br />select j.id, j.job_id, d.NAMES, e.DETAILS1, j.file_name, j.job_owner, j.import_date<br />from db.summary_jobs j<br />left join db.EST e on (j.job_id=e.JOB_NUMBER)<br />left join db.DEB d on (e.DEBTOR=d.AC_NO)<br />order by j.job_id desc limitTech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113733748505644782005-04-17T03:28:00.000-07:002005-04-17T03:29:08.506-07:00How to alter mysql table column to AUTO_INCREMENTmysql> set insert_id=7;<br /> Query OK, 0 rows affected (0.00 sec)<br /><br /> mysql> alter table fixtures modify column id int auto_increment;<br /> Query OK, 7 rows affected (0.01 sec)<br /> Records: 7 Duplicates: 0 WarningsTech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113733684459367382005-04-17T03:27:00.000-07:002005-04-17T03:28:04.460-07:00MySQL INSERT SELECT exampleinsert into user (id, name, email, passwd, ref, joindate) select idm, user_name, email, pass, refferal, sysdate() from db.members;Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.comtag:blogger.com,1999:blog-12233913.post-1113733554972229782005-04-17T03:25:00.000-07:002005-04-17T03:25:54.973-07:00Export from mysql into fixed length fileSELECT * INTO OUTFILE file_name<br />FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY ''<br />LINES TERMINATED BY "\n"<br />FROM my_table;Tech Journalisthttp://www.blogger.com/profile/06397377314569093942noreply@blogger.com