全国统一服务热线:400-633-9193

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

    网络     2018-06-29    1420

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

union关键字

1
2
3
4
5
6
7
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);

为表取别名

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

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

为字段取别名

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

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

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

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

1
2
3
4
5
6
7
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语句如下

1
2
3
4
5
6
7
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订单的下单日期

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

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

1
2
3
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的水果的名称

1
2
3
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

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


  分享到:  
0.2035s