亲宝软件园·资讯

展开

MySQL Union合并查询数据及表别名、字段别名用法分析

程志伟 人气:0
这篇文章主要介绍了MySQL Union合并查询数据及表别名、字段别名用法,结合实例形式较为详细的分析了mysql使用Union合并连接查询数据以及使用as实现表别名与字段别名操作,需要的朋友可以参考下

本文实例讲述了MySQL Union合并查询数据及表别名、字段别名用法。分享给大家供大家参考,具体如下:

union关键字

SELECT s_id, f_name, f_price
FROM fruits
WHERE f_price < 9.0
UNION ALL
SELECT s_id, f_name, f_price
FROM fruits
WHERE s_id IN(101,103);

为表取别名

SELECT * from orders AS o
WHERE o.o_num = 30001;

SELECT c.c_id, o.o_num
FROM customers AS c LEFT OUTER JOIN orders AS o
ON c.c_id = o.c_id;

为字段取别名

SELECT f1.f_name AS fruit_name, f1.f_price AS fruit_price
FROM fruits AS f1
WHERE f1.f_price < 8;

SELECT CONCAT(RTRIM(s_name) , ' (', RTRIM(s_city), ')')
FROM suppliers
ORDER BY s_name;

SELECT CONCAT(RTRIM(s_name) , ' (', RTRIM(s_city), ')')
as suppliers_title
FROM suppliers
ORDER BY s_name;

【例.62】查询所有价格小于9的水果的列表,查询s_id等于101和103所有的水果种类,使用UNION连接查询结果

SELECT s_id, f_name, f_price
FROM fruits
WHERE f_price < 9.0
UNION ALL
SELECT s_id, f_name, f_price
FROM fruits
WHERE s_id IN(101,103);

【例.63】查询所有价格小于9的水果的列表,查询s_id等于101和103所有的水果种类,使用UNION ALL连接查询结果,SQL语句如下

SELECT s_id, f_name, f_price
FROM fruits
WHERE f_price < 9.0
UNION ALL
SELECT s_id, f_name, f_price
FROM fruits
WHERE s_id IN(101,103);

【例.64】为orders表取别名o,查询订30001订单的下单日期

SELECT * from orders AS o
WHERE o.o_num = 30001;

【例.65】为customers和orders表分别取别名,并进行连接查询

SELECT c.c_id, o.o_num
FROM customers AS c LEFT OUTER JOIN orders AS o
ON c.c_id = o.c_id;

【例.66】查询fruits表,为f_name取别名fruit_name,f_price取别名fruit_price,为fruits表取别名f1,查询表中f_price < 8的水果的名称

SELECT f1.f_name AS fruit_name, f1.f_price AS fruit_price
FROM fruits AS f1
WHERE f1.f_price < 8;

【例.67】查询suppliers表中字段s_name和s_city,使用CONCAT函数连接这个两个字段值,并取列别名为suppliers_title

如果没有对连接后的值取别名,其显示列名称将会不够直观,输入如下SQL

SELECT CONCAT(RTRIM(s_name) , ' (', RTRIM(s_city), ')')
FROM suppliers
ORDER BY s_name;

希望本文所述对大家MySQL数据库计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论