Sie sind auf Seite 1von 44

MySql Programming

By
Jayaram P

1
 Introduction

2
Basic MySQL commands

• The following command lets you find out all the existing databases
show databases;

•Before using a database, you have to create it first.


create database college;
show databases;

•You also have to specify which database to use, before using it.

use college;

•Show all the tables in the current database that you have chosen to use.

show tables;

3
•Before using a database table, you have to create it first.

create table staff (


empId char(50) primary key,
empName char(50),
empDesignation char(50),
empDept char(50),
empEmail char(50),
empQualif char(50));

CREATE TABLE Student (


Id Integer,
Name Char(20) Not Null,
Address Char(50),
Status Char(10) Default ’freshman’
PRIMARY KEY (Id));
• To know the structure of the table use below query
desc staff ;
4
•Insert data into table
 Insert into staff values(‘emp1’,’empname’,………)
 Insert into Student (Id, Name, Address, Status)
Values (111111111, ’Jane Doe’, ’123 Main St.’, ’freshman’);
•Check the data available in table
select * from staff ;
• If made mistakes when creating a table useAlter Table command to correct them.

alter table staff change empQualif empQualification char(200) not null

Check for changes made

desc staff;
• To change the name of the table
alter table staff rename to Staff;

List the tables


show tables;
5
• To delete the table structure use below query

drop table staff;

•If you just want to delete some rows from a table,


delete from staff
where empId=‘…..’;

• To update the data available in table use below query

update staff
set empname=……
where empname=…….

6
 Specifying Which Columns and Rows to Select

• selecting all columns from staff table


select * from staff
•Selecting specific columns
select empId,empName from staff

 Naming Query Result Columns

•Problem
The column names in a query result are unsuitable, ugly, or difficult to
work with.
•Solution
Use aliases to choose your own column names.
•Query
select empDesignation as ‘Designation’ from staff

7
 Sorting Query Results
•Problem
Your query results aren’t sorted the way you want.
•Solution
MySQL can’t read your mind. Use an ORDER BY clause to tell it how to
sort result rows.
•Query

select * from staff where empDept =‘CS’ order by empQualif

• Default sorting order is ascending. Use desc keyword to sort in descending order.

select * from staff where empDept =‘CS’ order by empQualif desc

8
 Removing Duplicate Rows
•Problem
Output from a query contains duplicate rows. You want to eliminate
them.
•Solution
Use DISTINCT.
•Query

select distinct empQualif from staff

9
 Working with NULL Values

•Problem
You’re trying to to compare column values to NULL, but it isn’t working.
•Solution
Use the proper comparison operators: IS NULL, IS NOT NULL, or <=>.
•Query
select * from staff where empQualif IS NULL

select * from staff where empDept IS NOT NULL

•The MySQL-specific <=> comparison operator, unlike the = operator, is true even
for two NULL values:
SELECT NULL = NULL, NULL <=> NULL;

10
Writing Comparisons Involving NULL in Programs
•Problem
You’re writing a program that looks for rows containing a specific value,
but it fails when the value is NULL.
•Solution
Choose the proper comparison operator according to whether the
comparison value is or is not NULL.

•Query

select * from staff where empQualif = NULL

select * from staff where empQualif IS NULL

11
Using Views to Simplify Table Access

•Problem
You want to refer to values calculated from expressions without writing the
expressions each time you retrieve them.

•Solution
Use a view defined such that its columns perform the desired calculations.

•Query

create view staffView as


select empId,empName from staff

12
 Cloning a Table
•Problem
You want to create a table that has exactly the same structure as an existing
table.
•Solution
Use CREATE TABLE … LIKE to clone the table structure. To also copy
some or all of the rows from the original table to the new one, use INSERT INTO
… SELECT.
•Query

create table new_staff like staff

insert into new_staff select * from staff

13
Creating Temporary Tables
•Problem
You need a table only for a short time, after which you want it to
disappear automatically.
•Solution
Create a table using the TEMPORARY keyword, and let MySQL take
care of removing it.
•Query

1) Create the table from explicit column definitions:


CREATE TEMPORARY TABLE tbl_name (...column definitions...);

2) Create the table from an existing table:


CREATE TEMPORARY TABLE new_table LIKE original_table;

14
Working with Dates and Times
Choosing a Temporal Data Type
•Problem
You need to store temporal data but aren’t sure which is the most
appropriate data type.
•Solution
Choose the data type according to the characteristics of the information to
be stored and how you need to use it.

•To choose a temporal data type, consider questions such as these:

• Do you need times only, dates only, or combined date and time values?
• What range of values do you require?
• Do you want automatic initialization of the column to the current date
and time?

15
• MySQL provides following datatypes
1) DATE
•Have CCYY-MM-DD format, where CC, YY, MM, and DD represent the
century,year within century, month, and day parts of the date.
•The supported range for DATE values is 1000-01-01 to 9999-12-31.
2) TIME
•Have hh:mm:ss format, where hh, mm, and ss are the hours, minutes,
and seconds parts of the time.

3) DATETIME
•Combined date-and-time values in CCYY-MM-DD hh:mm:ss format.
4) TIMESTAMP
•Combined date-and-time values in CCYY-MM-DD hh:mm:ss format.

16
create table staff (
empId char(50) primary key,
empName char(50),
empDesignation char(50),
empDept char(50),
empEmail char(50),
empQualif char(50),
dob date
);

CREATE TABLE Student (


Id Integer,
Name Char(20) Not Null,
Address Char(50),
Status Char(10) default ’freshman’,
dob date,
PRIMARY KEY (Id));
17
• One way to rewrite non-ISO values for date entry is to use the
STR_TO_DATE() function

INSERT INTO staff (dob) VALUES(STR_TO_DATE('May 13, 2007','%M %d,


%Y'));
•To display dates or times in other formats, use the DATE_FORMAT() or
TIME_FORMAT() function to rewrite them.

SELECT dob, DATE_FORMAT(dob,'%M %d, %Y') as dateInFormat


FROM staff;

18
19
20
•TIME_FORMAT() is similar to DATE_FORMAT().
•It works with TIME, DATETIME, or TIMESTAMP values
•Understands only time-related specifiers in the format string

21
Determining the Current Date or Time
Problem
What’s today’s date? What time is it?

22
Using TIMESTAMP or DATETIME to Track Row-Modification
Times
•Problem
You want to record row-creation time or last modification time automatically.
•Solution
Use the auto-initialization and auto-update properties of the TIMESTAMP and
DATETIME data types.
•Query

CREATE TABLE tsdemo


(
val INT,
ts_both TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP,
ts_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
ts_update TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
23
24
Extracting Parts of Dates or Times
Problem
You want to obtain just a part of a date or a time.
Query

SELECT dob, DATE(dob), TIME(dob) FROM staff

25
26
Obtaining the Current Year, Month, Day, Hour, Minute, or Second

27
 Converting between dates and days
•TO_DAYS() converts a date to the corresponding number of days, and
FROM_DAYS() does the opposite

•Query

SELECT dob, TO_DAYS(dob) AS ‘Dob to days’,


FROM_DAYS(TO_DAYS(dob)) AS ‘DATE to days to DATE’
FROM staff

28
 Calculating Intervals Between Dates or Times
Problem
You want to know how long it is between two dates or times; that is, the
interval between them.
Solution
To calculate an interval, use one of the temporal-difference functions, or
convert your values to basic units and take the difference.

•Query

29
• To calculate an interval between TIME values as another TIME value, use the
TIMEDIFF() function:

30
Adding Date or Time Values
Problem
You want to add temporal values. For example, you want to add a given
number of seconds to a time or determine what the date will be three weeks from
today.

31
mysql> SET @dt = '1984-03-01 12:00:00', @t = '12:00:00';
mysql> SELECT ADDTIME(@dt,@t);

32
33
•Find the date a week ago:
SELECT CURDATE(), DATE_SUB(CURDATE(),INTERVAL 1 WEEK);

34
Calculating Ages
Problem
You want to know how old someone is.

35
Finding the Day of the Week for a Date
Problem
You want to know the day of the week on which a date falls.
Solution
Use the DAYNAME() function.

36
Importing and Exporting Data

 Importing Data with LOAD DATA and mysqlimport


Problem
You want to load a datafile into a table using MySQL’s built-in import capabilities.
Solution
Use the LOAD DATA statement or the mysqlimport command-line program.

•Query
1) LOAD DATA LOCAL INFILE 'E:\data.txt' INTO table faculty

2) LOAD DATA LOCAL INFILE 'E:\data.txt' INTO table faculty


FIELDS TERMINATED BY ','

37
 Exporting Query Results from MySQL
Problem
You want to export the result of a query from MySQL into a file or another
program.
Solution
Use the SELECT … INTO OUTFILE statement, or redirect the output of
the mysql program.
•Query

SELECT * FROM faculty INTO OUTFILE 'E:\\faculty.txt' FIELDS


TERMINATED BY ',' LINES TERMINATED BY '\r\n'

38
39
40
41
42
43
44

Das könnte Ihnen auch gefallen