详解MySQL中UNION的用法
程序员文章站
2024-02-29 16:56:52
如果想选择其他几个表中的行或从一个单一的表作为一个单独的结果集行的几个集会,那么可以使用的union。
union在mysql4.0以上版本才能可以使用。本节说明如何使用...
如果想选择其他几个表中的行或从一个单一的表作为一个单独的结果集行的几个集会,那么可以使用的union。
union在mysql4.0以上版本才能可以使用。本节说明如何使用它。
假设有两个表,潜在和实际的客户列表,供应商购买耗材合并所有三个表中的姓名和地址,来创建一个单一的邮件列表。union提供了一种方法做到这一点。假设三个表有以下内容:
mysql> select * from prospect; +---------+-------+------------------------+ | fname | lname | addr | +---------+-------+------------------------+ | peter | jones | 482 rush st., apt. 402 | | bernice | smith | 916 maple dr. | +---------+-------+------------------------+ mysql> select * from customer; +-----------+------------+---------------------+ | last_name | first_name | address | +-----------+------------+---------------------+ | peterson | grace | 16055 seminole ave. | | smith | bernice | 916 maple dr. | | brown | walter | 8602 1st st. | +-----------+------------+---------------------+ mysql> select * from vendor; +-------------------+---------------------+ | company | street | +-------------------+---------------------+ | reddyparts, inc. | 38 industrial blvd. | | parts-to-go, ltd. | 213b commerce park. | +-------------------+---------------------+
这不要紧,如果所有的三个表具有不同的列名。下面的查询演示了如何选择一下子从三个表的名称和地址:
mysql> select fname, lname, addr from prospect -> union -> select first_name, last_name, address from customer -> union -> select company, '', street from vendor; +-------------------+----------+------------------------+ | fname | lname | addr | +-------------------+----------+------------------------+ | peter | jones | 482 rush st., apt. 402 | | bernice | smith | 916 maple dr. | | grace | peterson | 16055 seminole ave. | | walter | brown | 8602 1st st. | | reddyparts, inc. | | 38 industrial blvd. | | parts-to-go, ltd. | | 213b commerce park. | +-------------------+----------+------------------------+
如果想选择所有记录,包括重复的,请all的第一个union关键字:
mysql> select fname, lname, addr from prospect -> union all -> select first_name, last_name, address from customer -> union -> select company, '', street from vendor; +-------------------+----------+------------------------+ | fname | lname | addr | +-------------------+----------+------------------------+ | peter | jones | 482 rush st., apt. 402 | | bernice | smith | 916 maple dr. | | grace | peterson | 16055 seminole ave. | | bernice | smith | 916 maple dr. | | walter | brown | 8602 1st st. | | reddyparts, inc. | | 38 industrial blvd. | | parts-to-go, ltd. | | 213b commerce park. | +-------------------+----------+------------------------+
下一篇: Android下的EXIF是什么