MySQL Union合并查询数据及表别名、字段别名 MySQL Union合并查询数据及表别名、字段别名用法分析
程志伟 人气:0本文实例讲述了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数据库计有所帮助。
加载全部内容