วันพุธที่ 17 ธันวาคม พ.ศ. 2557

คำสั่ง SQL ALIAS

คำสั่ง SQL ALIAS

เป็นคำสั่งที่ใช้สำหรับการระบุเงื่อนไขการเลือกข้อมูลในตาราง (Table) โดย ALIAS คือการสร้างชื่อจำลองขึ้นมาใหม่ โดยสามารถจำลองชื่อได้ทั้งชื่อ Field และชื่อ Table 

Database : MySQL 

Syntax
SELECT Column1 AS Alias1,Column2 AS Alias2,Column3 AS Alias3,... FROM [Table-Name1] Table Alias

Table : customer
CustomerID
Name
Email
CountryCode
Budget
Used
C001
Win Weerachaiwin.weerachai@thaicreate.com
TH
1000000600000
C002
John Smithjohn.smith@thaicreate.com
EN
2000000800000
C003
Jame Bornjame.born@thaicreate.com
US
3000000600000
C004
Chalee Angelchalee.angel@thaicreate.com
US
4000000100000

Sample1 การเลือกข้อมูลตาราง customer โดยทำการ Alias เปลี่ยนชื่อฟิวด์ขึ้นมาใหม่
SELECT CustomerID AS CusID,Name AS CusName,Email AS CusEmail FROM customer

Output 
CusID
CusName
CusEmail
C001
Win Weerachaiwin.weerachai@thaicreate.com
C002
John Smithjohn.smith@thaicreate.com
C003
Jame Bornjame.smith@thaicreate.com
C004
Chalee Angelchalee.angel@thaicreate.com
Sample2 การเลือกข้อมูลตาราง customer,audit โดยทำการ Alias เปลี่ยนชื่อ Table เพื่อง่านต่อการเรียกใช้งาน 
SELECT X.*,Y.* FROM customer X
LEFT JOIN audit Y ON X.CustomerID = Y.CustomerID
WHERE X.CustomerID = 'C001'

Output 
CustomerID
Name
Email
CountryCode
Budget
Used
AuditID
CustomerID
Date
Used
C001
Win Weerachaiwin.weerachai@thaicreate.com
TH
1000000600000
1
C001
2008-08-01
100000
C001
Win Weerachaiwin.weerachai@thaicreate.com
TH
1000000600000
2
C001
2008-08-05
200000
C001
Win Weerachaiwin.weerachai@thaicreate.com
TH
1000000600000
3
C001
2008-08-10
300000

Sample3 การเลือกข้อมูลตาราง customer โดยทำการ Alias เปลี่ยนชื่อ Table เพื่อง่านต่อการเรียกใช้งาน 
SELECT X.CustomerID,X.Name FROM customer X

Output 
CusID
CusName
C001
Win Weerachai
C002
John Smith
C003
Jame Born
C004
Chalee Angel

ไม่มีความคิดเห็น:

แสดงความคิดเห็น