6个有用的MySQL查询技巧

On 2010年12月30日, in database, tips, by netoearth

The art of query building is the art of using Structured Query Language to formulate correct, efficient database questions and commands. In SELECT queries, you can use JOIN, WHERE and HAVING clauses to scope the result to specific rows and columns, GROUP BY to combine result rows into analytic summaries, and UNION to combine the results of multiple queries. INSERT, DELETE and UPDATE commands may reference JOINs. INSERT … SELECT inserts a query result into another table. DELETEs and UPDATEs may be scoped by WHERE clauses.

1. Age in years

You have a birth date and need to calculate how old is the guy. Assume the @dateofbirth is this date:

1 SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(now()) - TO_DAYS(@dateofbirth)), '%Y') + 0;

2. Difference between two dates

Find the difference between two datetime values in seconds, minutes, hours or days. If dt1 and dt2 are datetime values of the form ‘yyyy-mm-dd hh:mm:ss’, the number of seconds between dt1 and dt2 is

1 UNIX_TIMESTAMP( dt2 ) - UNIX_TIMESTAMP( dt1 )

To get the number of minutes divide by 60, for the number of hours divide by 3600, and for the number of days, divide by 3600 * 24.

3. Display column values which occur N times

1 SELECT id
2 FROM tbl
3 GROUP BY id
4 HAVING COUNT(*) = N;

4. Count business days between two dates

The simplest support for counting business days between any two dates is a calendar table with columns d date and holiday bool populated for all days in all possibly relevant years. Then the following query gives the inclusive number of business days between dates Start and Stop:

1 SELECT COUNT(*)
2 FROM calendar
3 WHERE d BETWEEN Start AND Stop
4 AND DAYOFWEEK(d) NOT IN(1,7)
5 AND holiday=0;

5. Find primary key of the table

1 SELECT k.column_name
2 FROM information_schema.table_constraints t
3 JOIN information_schema.key_column_usage k
4 USING (constraint_name,table_schema,table_name)
5 WHERE t.constraint_type='PRIMARY KEY'
6 AND t.table_schema='db'
7 AND t.table_name='tbl'

6. Find out how big is your database

1 SELECT
2 table_schema AS 'Db Name',
3 Round( Sum( data_length + index_length ) / 1024 / 1024, 3 ) AS 'Db Size (MB)',
4 Round( Sum( data_free ) / 1024 / 1024, 3 ) AS 'Free Space (MB)'
5 FROM information_schema.tables
6 GROUP BY table_schema ;

I hope that this not so common queries will help you out.

Tagged with:  

Comments are closed.