RSS
email
0

View MySql


Views

VIEW is a virtual table, which acts like a table but actually it contains no data. That is based on the result set of a SELECT statement. A VIEW consists rows and columns from one or more than one tables. A VIEW is a query that’s stored as an object. A VIEW is nothing more than a way to select a subset of table’s columns.
When you defined a view then you can reference it like any other table in a database. A VIEW provides as a security mechanism also. VIEWS ensures that users are able to modify and retrieve only that data which seen by them. 

By using Views you can ensure about the security of data by restricting access to the following data:
  • Specific columns of the tables. 
    Specific rows of the tables. 
  • Specific rows and columns of the tables. 

  • Subsets of another view or a subset of views and tables
  • Rows fetched by using joins. 
  • Statistical summary of data in a given tables. 


CREATE VIEW Statement
     
CREATE VIEW Statement is used to create a new database view. The general syntax of CREATE VIEW Statement is:
        CREATE VIEW view_name [(column_list)] [WITH ENCRYPTION] AS select_statement [WITH CHECK OPTION]
View_name specifies the name for the new view. column_list specifies the name of the columns to be used in view. column_list must have the same number of columns that specified in select_statement. If column_list option is not available then view is created with the same columns that specified in select_statement.
WITH ENCRYPTION option encrypts the text to the view in the syscomments table.
AS option specifies the action that is performed by the view. select_statement is used to specify the SELECT statement that defines a view. The optional WITH CHECK OPTION clause applies to the data modification statement like INSERT and UPDATE statements to fulfill the criteria given in the select_statement defining the view. This option also ensures that the data can visible after the modifications are made permanent.
Some restrictions imposed on views are given below :
  • A view can be created only in the current database. 
    The view name must follow the rules for identifiers and 

  • The view name must not be the same as that of the base table
  • A view can be created only that time if there is a SELECT permission on its base table. 
  • A SELECT INTO statement cannot be used in view declaration statement. 
  • A trigger or an index cannot be defined on a view. 
  • The CREATE VIEW statement cannot be combined with other SQL statements in a single batch. 

Example :
In the following example we have two table Client and Products. And if you want to see only those client records that are active in Products table also means right now they are supplying us the products. For this we are creating the view by the name of Supp_Client.

mysql> SELECT * FROM Client;
+------+---------------+----------+
| C_ID | Name | City |
+------+---------------+----------+
| 1 | A K Ltd | Delhi |
| 2 | V K Associate | Mumbai |
| 3 | R K India | Banglore |
| 4 | R S P Ltd | Kolkata |
| 5 | A T Ltd | Delhi |
| 6 | D T Info | Delhi |
+------+---------------+----------+
6 rows in set (0.00 sec)
mysql> SELECT * FROM Products;
+---------+-------------+------+
| Prod_ID | Prod_Detail | C_ID |
+---------+-------------+------+
| 111 | Monitor | 1 |
| 112 | Processor | 2 |
| 113 | Keyboard | 2 |
| 114 | Mouse | 3 |
| 115 | CPU | 5 |
+---------+-------------+------+
5 rows in set (0.00 sec)
       
Example : Create View Statement
         

mysql> CREATE VIEW Supp_Client AS
-> SELECT * FROM Client
-> WHERE C_ID IN (
-> SELECT C_ID FROM Products)
-> WITH CHECK OPTION;
Query OK, 0 rows affected (0.05 sec)
mysql> SELECT * FROM Supp_Client;
+------+---------------+----------+
| C_ID | Name | City |
+------+---------------+----------+
| 1 | A K Ltd | Delhi |
| 2 | V K Associate | Mumbai |
| 3 | R K India | Banglore |
| 5 | A T Ltd | Delhi |
+------+---------------+----------+
4 rows in set (0.03 sec)
In the following example we include the WHERE clause with the select statement of view. Then MySQL adds this condition to the VIEW definition when executing the statement for further restricting the result. Example :
mysql> SELECT * FROM Supp_Client WHERE City='Delhi';
+------+---------+-------+
| C_ID | Name | City |
+------+---------+-------+
| 1 | A K Ltd | Delhi |
| 5 | A T Ltd | Delhi |
+------+---------+-------+
2 rows in set (0.04 sec)
ALTER VIEW Statement
By the ALTER VIEW Statement we can change the definition of a view. This statement is useful to modify a view without dropping it. ALTER VIEW statement syntax is similar to CREATE VIEW Statement and effect is same as the CREATE OR REPLACE VIEW. The general syntax of ALTER VIEW Statement is :
        ALTER VIEW view_name [(column_list)] [WITH ENCRYPTION] AS select_statement [WITH CHECK OPTION]
In the following example we are altering the view definition that we have created above. In this we add one more column by the name of Prod_Detail of Products table. Example of Altering the View Statement :
mysql> ALTER VIEW Supp_Client AS
-> SELECT Client.C_ID, Client.Name, Client.City,
-> Products.Prod_Detail from Client, Products
-> WHERE Client.C_ID=Products.C_ID;
Query OK, 0 rows affected (0.01 sec)
mysql> SELECT * FROM Supp_Client;
+------+---------------+----------+-------------+
| C_ID | Name | City | Prod_Detail |
+------+---------------+----------+-------------+
| 1 | A K Ltd | Delhi | Monitor |
| 2 | V K Associate | Mumbai | Processor |
| 2 | V K Associate | Mumbai | Keyboard |
| 3 | R K India | Banglore | Mouse |
| 5 | A T Ltd | Delhi | CPU |
+------+---------------+----------+-------------+
5 rows in set (0.02 sec)
DROP VIEW Statement
For dropping a view you can use the DROP VIEW Statement. When view is dropped but it has no effect on the underlying tables. After dropping a view if you issue any query that reference a dropped view then you get an error message. But dropping a table that reference any view does not drop the view automatically you have to dropt the view explicitly. The general syntax of DROP VIEW Statement is :
       
DROP VIEW view_name;
In the following example we are dropping the view that we have created above. Example of Dropping the View Statement :
mysql> DROP VIEW Supp_Client;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM Supp_Client;
ERROR 1146 (42S02): Table 'employee.supp_client' doesn't exist


Contoh Implemetasi View:
1. Membuat Tabel barang:






mysql> create table barang
   -> (kode_barang char(3) not null primary key default'0',
   -> nama_barang char(30),
   -> harga_barang int);
Query OK, 0 rows affected (0.05 sec)


mysql> insert into barang
    -> value
    -> ('001', 'mobil',5000000);
Query OK, 1 row affected (0.01 sec)


2. Membuat Tabel Jual
mysql> create table jual
    -> (tgl date,
    -> kode char(3), jml_jual int);
Query OK, 0 rows affected (0.03 sec)


mysql> insert into jual
    -> value
    -> ('2007/01/01','001',3);
Query OK, 1 row affected (0.03 sec)


3. Membuat View
mysql> create view jualan_view as select date_format(b.tgl,'%d%M%Y')as tgl, b.ko
de, a.nama_barang, a.harga_barang, b.jml_jual,(a.harga_barang*b.jml_jual) as tot
al from jual b, barang a where b.kode=a.kode_barang;
Query OK, 0 rows affected (0.00 sec)


mysql> select* from jualan_view;
+---------------+------+-------------+--------------+----------+----------+
| tgl           | kode | nama_barang | harga_barang | jml_jual | total    |
+---------------+------+-------------+--------------+----------+----------+
| 01January2007 | 001  | mobil       |      5000000 |        3 | 15000000 |
+---------------+------+-------------+--------------+----------+----------+
1 row in set (0.00 sec)


mysql> select* from jual;
+------------+------+----------+
| tgl        | kode | jml_jual |
+------------+------+----------+
| 2007-01-01 | 001  |        3 |
+------------+------+----------+
1 row in set (0.00 sec)


mysql> select* from jualan_view;



Read more
0

Dasar MySql



Pertemuan ke 2
(Structured Query Language /SQL)


Structured Query Language (SQL) merupakan bahasa yang banyak digunakan dalam berbagai produk database. SQL dibangun di laboratorium IBM-San Jose California sekitar akhir tahun 70-an. Pertama kali dikembangkan sebagai bahasa di produk database DB2 yang sampai saat ini merupakan produk database andalan IBM. SQL sering di lafalkan dengan “sequel”.

Saat ini organisasi standar America (ANSI) menetapkan standar bahasa SQL yaitu ANSI-92 standard. Masing-masing vendor database memiliki dialeknya sendiri sebagaian besar spesifikasinya mengacu pada standar ANSI tersebut dengan berbagai ekstensi tambahan. SQL Server menggunakan bahasa Transact-SQL dalam produknya, sedangkan Oracle menggunakan PL/SQL.


1. Dasar SQL

Fungsi paling dasar dari SQL adalah untuk menampilkan data dari database. Data tersebut selanjutnya dapat difilter dan dimanipulasi sesuai kebutuhan aplikasi.

Perintah perintah dalam SQL terbagi dalam 2 kelompok besar :

• Data Manipulation Language

• Data Definition Language

2. Bekerja dengan MySQL

Untuk menjalankan MySQL dari menu Windows: Start -> Programs -> MySQL ->MySQL Server 5.0 -> MySQL Command Line Client.
Isikan password yang telah dibuat pada saat instalasi MySQL, jika ada password.
Enter password: ******
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 60
Server version: 5.0.45-community-nt MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
Menampilkan database
Kita coba dengan perintah "SHOW DATABASES" yang akan menampilkan database yang ada di dalam sistem MySQL kita.
mysql> show databases ;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| test |
--------------------- +
3 rows in set (0.00 sec)

Membuat database baru
Sudah ada 3 buah database di dalam sistem MySQL. Sekarang kita akan membuat sebuah database untuk latihan kita. Gunakan perintah "CREATE DATABASE" untuk membuat sebuah database.
mysql> create database Coba1 ;
Query OK, 1 row affected (0.02 sec)

Anda perhatikan dari dua perintah MySQL di atas,bahwa setiap perintah selalu diakhiri dengan tanda ";" (titik-koma). Memang pada umumnya perintah-perintah MySQL diakhiri oleh tanda ";" ini. Perhatikan perintah dibawah ini bila ditulis tanpa tanda titik-koma ";'.
mysql> create database coba2
->
Sistem MySQL akan menampilkan tanda panah '->' yang menyatakan bahwa perintah MySQL tersebut dianggap belum selesai (karena belum diakhiri dengan tanda titik-koma ';').
Sekarang kita lengkapi perintah sebelumnya dengan tanda titik-koma ';'
mysql> create database coba2
-> ;
Query OK, 1 row affected (0.02 sec)
Kita periksa lagi hasil dari perintah di atas dengan "SHOW DATABASE".
Perintah:
mysql> show databases ;
+-------------------- +
| Database |
+-------------------- +
| information_schema |
| coba1 |
|coba2 |
| mysql |
| test |
+--------------------+
5 rows in set (0.00 sec)



Menghapus database
Jika kita akan menghapus database coba2, dapat dilakukan dengan perintah DROP DATABASE.

Jika kita menggunakan perintah DROP DATABASE , maka database beserta isi akan terhapus.

mysql> drop database coba2 ;
Query OK, 0 row affected (0.02 sec)
Anda bisa memeriksanya lagi hasil dari perintah di atas dengan "SHOW DATABASE".
mysql> show databases ;
+--------------------+
| Database |
+--------------------+
| information_schema |
| coba1 |
| mysql |
| test |
+--------------------+
4 rows in set (0.00 sec)
database coba2 sudah hilang.

Memilih dan membuka sebuah database
Sekarang pilih database "coba1" dan kita buka dengan perintah "USE"
mysql> use coba1 ;
Database change

Melihat isi sebuah database
Untuk melihat apa isi dari sebuah database, kita gunakan perintah "SHOW TABLES". Mari kita
coba.
mysql> show tables ;
Empty set (0.00 sec)
Hasil dari perintah SHOW TABLES diatas adalah "Empty Set", yang berarti belum ada table apapun didalam database coba1.

I. MEMBUAT TABEL

Kita akan membuat sebuah tabel baru dengan menggunakan perintah "CREATE TABLE".
Contohnya sebagai berikut..
mysql> create table karyawan
-> (kopeg INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
-> nama VARCHAR(30) NOT NULL)
-> ;
Query OK, 0 rows affected (0.14 sec)
Secara umum, kita akan membuat sebuah
tabel Karyawan dengan 2 buah kolom/field. Kolom pertama adalah KOPEG dengan jenis data bilangan bulat (INTeger), tanpa tanda negatif (UNSIGNED), yang akan bertambah nilainya secara otomatis (AUTO_INCREMENT), dan kolom KOPEG adalah kolom utama (PRIMARY KEY).
Kemudian pada kolom kedua, NAMA akan menampung nama karyawan, dengan jenis data
VARiabel CHARacter, lebar datanya dapat menampung maksimal 30 karakter, dan tidak boleh dikosongkan (NOT NULL).
Jika kita mau melihat isi dari database coba1:
mysql> show tables ;
+--------------------+
| Tables_in_latihan1 |
+--------------------+
| karyawan |
+--------------------+
1 row in set (0.00 sec)
Dari hasil perintah di atas, kita lihat bahwa database coba1 telah memiliki sebuah tabel yang bernama karyawan.

1. Membuat table:

CREATE TABLE `coba2`.`pegawai` (
`nip` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`nama` VARCHAR(45) NOT NULL,
`alamat` VARCHAR(45),
PRIMARY KEY(`nip`)
)
ENGINE = InnoDB;

Melihat struktur tabel
Untuk melihat struktur sebuah tabel dapat menggunakan perintah "DESCRIBE" atau bisa juga menggunakan perintah "SHOW COLUMNS FROM". Contohnya berikut ini...
mysql> describe karyawan ;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| kopeg | int(10) unsigned | NO | PRI | NULLauto_increment |
| nama | varchar(30) | NO | | | |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.02 sec)
Atau menggunakan perintah "SHOW COLUMNS FROM..."
mysql> show columns from karyawan ;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| kopeg | int(10) unsigned | NO | PRI | NULL | auto_increment |
| nama | varchar(30) | NO | | | |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
Tidak ada perbedaan hasil dari dua perintah di atas.
Sekarang kita buat sebuah tabel lagi.
mysql> create table contoh1
-> (noid INT)
-> ;
Query OK, 0 rows affected (0.13 sec)
Sekarang kita lihat berapa tabel yang ada di dalam database contoh1:
mysql> show tables ;
+--------------------+
| Tables_in_coba1 |
+--------------------+
| contoh1 |
| karyawan |
+--------------------+
2 rows in set (0.00 sec)

Menghapus table
Menghapus sebuah tabel dalam MySQL dilakukan dengan perintah "DROPTABLE".
mysql> drop table contoh1 ;
Query OK, 0 rows affected (0.03 sec)
Kita lihat lagi tabel yang ada di dalam database coba1:
mysql> show tables ;
+--------------------+
| Tables_in_coba1 |
+--------------------+
| karyawan |
+--------------------+
1 rows in set (0.00 sec)
Mengubah struktur sebuah tabel
Pengubahan struktur dapat dilakukan untuk:
a. Penambahan kolom (ADD),
b. pengubahan lebar dan jenis kolom (MODIFY)
c. penghapusan kolom dan indeks (DROP),
d. penggantian nama kolom (CHANGE),
e. pengantian nama tabel (RENAME), dan sebagainya.
f. Apa pun juga yang anda lakukan pada kolom
Misalnya kita akan menambahkan beberapa kolom baru, yaitu kolom jenis kelamin, kota, tanggal lahir dan kodepos pada tabel karyawan.
Perintah untuk mengubah struktur tabel adalah "ALTER TABLE". Mari kita coba...
mysql> alter table karyawan
-> ADD jenkelamin CHAR(2) NOT NULL,
-> ADD kota VARCHAR(25) NOT NULL,
-> ADD kodepos CHAR(5) NOT NULL,
-> ADD tgllahir DATE
-> ;
Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0
Sekarang kita lihat hasilnya:
mysql> describe karyawan ;
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| kopeg | int(10) | NO | PRI | NULL | auto_increment |
| nama | varchar(30) | NO | | | |
| jenkelamin | char(2) | YES | | NULL | |
| kota | varchar(25) | NO | | | |
| kodepos | char(5) | NO | | | |
| tgllahir | date | YES | | NULL | |
+------------+-------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
Jika kita ingin mengubah nama kolom kopeg menjadi id. Nama kolom jenkelamin, diubah menjadi jk. Dalam pengubahan kolom ini sebaiknya
'sifat-sifat' kolom yang asli tetap ditulis ulang. Misal bila kolom kopeg memiliki sifat 'auto_increment', maka selama sifat itu tetap dipertahankan, maka dia (auto_increment) harus ditulis ulang. Begini caranya...
Mengubah kolom jenkelamin menjadi jk, sekaligus mengubah jenis datanya dari CHAR(2)
menjadi CHAR(1):
mysql> alter table karyawan
-> change jenkelamin jk char(1) ;
Query OK, 0 rows affected (0.24 sec)
Records: 0 Duplicates: 0 Warnings: 0
Mengubah kolom kopeg menjadi id, tanpa mengubah jenis datanya (tetap INT(10), dan tetap (auto_increment):
mysql> alter table karyawan
-> change kopeg id int(10) auto_increment
-> ;
Query OK, 0 rows affected (0.16 sec)
Records: 0 Duplicates: 0 Warnings: 0
Sekarang kita lihat struktur tabel setelah pengubahan:
mysql> describe karyawan ;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(10) | NO | PRI | NULL | auto_increment |
| nama | varchar(30) | NO | | | |
| jk | char(1) | YES | | NULL | |
| kota | varchar(25) | NO | | | |
| kodepos | char(5) | NO | | | |
| tgllahir | date | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
Jika ingin mengubah nama tabel karyawan menjadi tabel pegawaidapaat dilakukan denga perintah seperti di bawah ini
mysql> alter table karyawan
-> rename pegawai ;
Query OK, 0 rows affected (0.09 sec)
Kita lihat lagi hasilnya:
mysql> show tables ;
+--------------------+
| Tables_in_latihan1 |
+--------------------+
| pegawai |
+--------------------+
1 row in set (0.00 sec)
Sekarang kita kembalikan lagi nama tabel pegawai menjadi karyawan. Tetapi dengan perintah yang
berbeda, yaitu "RENAME TABLE".
mysql> rename table pegawai
-> to karyawan
-> ;
Query OK, 0 rows affected (0.06 sec)
Jangan lupa untuk memeriksa hasilnya:
mysql> show tables ;
+--------------------+
| Tables_in_latihan1 |
+--------------------+
| karyawan |
+--------------------+
1 row in set (0.00 sec)

2. Mengisi table :
Kita akan mulai mengisi data karyawan ke dalam tabel. Perintah yang digunakan adalah "INSERT INTO". Caranya sebagai berikut:
mysql> insert into karyawan
-> (nama, jenkel, kota, kodepos, tgllahir)
-> values
-> ("Dewi Suharti", "P", "Yogyakarta","41011","1988-11-02")
-> ;
Query OK, 1 row affected (0.17 sec)
Pemasukkan data yang berjenis karakter, selalu diapit dengan tanda
kutip ganda ("). Bisa juga digunakan tanda kutip tunggal ('). Tetapi jangan dicampur dengan tanda kutip ganda dan tanda kutip tunggal, misal: "Dewi Suhartii'. Perhatikan juga pada penulisan tanggal
lahir, menggunakan format "tahun-bulan-tanggal". Standar MySQL untuk format penulisan tanggal. Kita tidak memasukkan data untuk kolom "id"? Ini karena sifat kolom id yang auto_increment, sehingga dia akan secara otomatis berisi dengan angka 1, dan terus bertambah 1, seiring dengan penambahan data.
Nah, kita akan masukkan 4 buah record lagi dengan cara:
mysql> insert into karyawan
-> (nama, jenkel, kota, kodepos, tgllahir)
-> values
-> ("Sundariwati", "P", "Bandung", "40123", "1978-11-12"),
-> ("Ryan Cakep", "L", "Jakarta", "12111", "1981-03-21"),
-> ("Zukarman","L", "Bekasi", "17211", "1978-08-10"),
-> ("Yuliawati", "P", "Bogor", "00000", "1982-06-09")
-> ;
Query OK, 4 rows affected (0.05 sec)
Records: 4 Duplicates: 0 Warnings: 0

insert into pegawai (nip,nama,alamat)
values (1324,'Andi','sleman')
Sekarang kita coba memasukkan data dengan cara yang lain lagi:
mysql> insert into karyawan
-> set nama="Mawar",
-> jenkel="P",
-> kota="Bogor",
-> kodepos="12345",
-> tgllahir="1985-07-07"
-> ;
Query OK, 1 row affected (0.05 sec)


Read more
 

Friends

ON-LINE