例子:vendors表包含供應商名和位置信息。假如要生成一個供應商報表,需要在供應商的名字中按照name(location)這樣的格式列出供應商信息。此報表需要單個值,而表中數據存儲在兩個列vend_name和vend_country中,此外,需要用括號將vend_country括起來,這些東西都沒有明確存儲在數據表中,我們來看看怎麼樣編寫返回供應商名和位置的select語句
SELECT CONCAT(vend_name, ' (',vend_country,')') FROM vendors ORDER BY vend_name;
這裡用到了concat函數,拼接串,即把多個串連接起來形成一個較長的串,concat需要一個或者多個指定的串,各個串之間用逗號分隔
SELECT CONCAT(RTRIM(vend_name),' (',RTRIM(vend_country),')') FROM vendors ORDER BY vend_name;
rtrim函數去掉值右邊的所有空格,通過使用rtrim(),各個列都進行了整理
SELECT CONCAT(RTRIM(vend_id),' (',RTRIM(vend_country),')') AS vend_title FROM vendors ORDER BY vend_name;
SELECT prod_id ,quantity ,item_price FROM orderitems WHERE order_num = 20005;
SELECT prod_id ,quantity ,item_price, quantity*item_price AS expanded_price FROM orderitems WHERE order_num = 20005;
upper()函數
SELECT vend_name ,UPPER(vend_name) AS vend_name_upcase FROM vendors ORDER BY vend_name;
函數 說明
Left() 返回串左邊的字符
Length() 返回串的長度
Locate() 找出串的一個子串
Lower() 將串轉換為小寫
LTrim() 去掉串左邊的空格
Right() 返回串右邊的字符
RTrim() 去掉串右邊的空格
Soundex() 返回串的soundex值
SubString() 返回子串的字符
upper() 將串轉為大寫
SELECT cust_name , cust_contact FROM customers WHERE SOUNDEX(cust_contact)=SOUNDEX('Y lie');
查找與lie發音相似的cust_contact的列
SELECT cust_id , order_num FROM orders WHERE order_date = '2005-09-01';
SELECT cust_id , order_num FROM orders WHERE DATE(order_date) = '2005-09-01';
SELECT cust_id , order_num ,order_date FROM orders WHERE DATE(order_date) BETWEEN '2005-09-01' AND '2005-09-30';
SELECT cust_id ,order_num,order_date FROM orders WHERE YEAR(order_date)= 2005 AND MONTH(order_date)= 9;
9月份的所有訂單
SELECT CONCAT(vend_name, ' (',vend_country,')') FROM vendors ORDER BY vend_name; SELECT CONCAT(RTRIM(vend_name),' (',RTRIM(vend_country),')') FROM vendors ORDER BY vend_name; SELECT CONCAT(RTRIM(vend_id),' (',RTRIM(vend_country),')') AS vend_title FROM vendors ORDER BY vend_name; SELECT prod_id ,quantity ,item_price FROM orderitems WHERE order_num = 20005; SELECT prod_id ,quantity ,item_price, quantity*item_price AS expanded_price FROM orderitems WHERE order_num = 20005; SELECT vend_name ,UPPER(vend_name) AS vend_name_upcase FROM vendors ORDER BY vend_name; SELECT cust_name , cust_contact FROM customers WHERE SOUNDEX(cust_contact)=SOUNDEX('Y lie'); SELECT cust_name , cust_contact FROM customers; SELECT cust_id , order_num FROM orders WHERE order_date = '2005-09-01'; SELECT cust_id , order_num FROM orders WHERE DATE(order_date) = '2005-09-01'; SELECT cust_id , order_num ,order_date FROM orders WHERE DATE(order_date) BETWEEN '2005-09-01' AND '2005-09-30'; SELECT cust_id ,order_num,order_date FROM orders WHERE YEAR(order_date)= 2005 AND MONTH(order_date)= 9;