วันอาทิตย์ที่ 14 ธันวาคม พ.ศ. 2557

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 Weerachai
win.weerachai@thaicreate.com
TH
1000000
600000
C002
John Smith
john.smith@thaicreate.com
EN
2000000
800000
C003
Jame Born
jame.born@thaicreate.com
US
3000000
600000
C004
Chalee Angel
chalee.angel@thaicreate.com
US
4000000
100000

Sample1 การเลือกข้อมูลตาราง customer โดยทำการ Alias เปลี่ยนชื่อฟิวด์ขึ้นมาใหม่

SELECT CustomerID AS CusID,Name AS CusName,Email AS CusEmail FROM customer

Output

CusID
CusName
CusEmail
C001
Win Weerachai
win.weerachai@thaicreate.com
C002
John Smith
john.smith@thaicreate.com
C003
Jame Born
jame.smith@thaicreate.com
C004
Chalee Angel
chalee.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
AuditID
CustomerID
Date
Used
C001
Win Weerachai
win.weerachai@thaicreate.com
TH
1000000
1
C001
2008-08-01
100000
C001
Win Weerachai
win.weerachai@thaicreate.com
TH
1000000
2
C001
2008-08-05
200000
C001
Win Weerachai
win.weerachai@thaicreate.com
TH
1000000
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

ที่มา : http://www.thaicreate.com/tutorial/sql-alias.html


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

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