假设我在MySQL中有2个表:
create table `persons` (
`id` bigint unsigned not null auto_increment,
`first_name` varchar(64),
`surname` varchar(64),
primary key(`id`)
);
create table `companies` (
`id` bigint unsigned not null auto_increment,
`name` varchar(128),
primary key(`id`)
);
Run Code Online (Sandbox Code Playgroud)
现在,我经常需要对它们进行相同的处理,这就是以下查询的原因:
select person.id as `id`, concat(person.first_name, ' ', person.surname) as `name`, 'person' as `person_type`
from persons
union all
select company.id as `id`, company.name as `name`, 'company' as `person_type`
from companies
Run Code Online (Sandbox Code Playgroud)
开始频繁出现在其他查询中:作为联接或子选择的一部分。现在,我只是将查询插入到联接或子选择中,例如:
select *
from some_table row
left …Run Code Online (Sandbox Code Playgroud)