加入2个选择结果 - 同时设置多个别名

时间:2014-01-30 16:47:48

标签: sql mysql-workbench

嗨,我对此很新,很抱歉,如果不解释这一点。

我有两个表(委托和模块)都有列名,例如“no”和“name”,这些都是重复的

我想要实现的是得到4个表的结果。

继承我的编码:

SELECT no AS del_no, name AS del_name
 FROM delegate

Union ALL

 SELECT code AS module_code, name AS module_name
 FROM module;

我的结果是两列,其中包含堆放在下面的模块的所有内容 但我真正想要的是来自2个不同表格的4个colums。

我无法更改列名,因为这符合我的要求。

1 个答案:

答案 0 :(得分:0)

有两种方法可以做到这一点,第一种方法是将结果组合到共享列中,如此

select t, shared, name from
(
  SELECT 1 as ordering, 'del_no' as t, no AS shared, name FROM delegate
  Union ALL
  SELECT 2 as ordering, 'module' as t, code AS shared, name FROM module
) sub
order by ordering asc

在第二个数据类型中,每个数据类型都有自己的列

select del_name, module_name, name from
(
  SELECT 1 as ordering, no as del_name, null as module_name, name FROM delegate
  Union ALL
  SELECT 2 as ordering, null as del_name, code as module_name, name FROM module
) sub
order by ordering asc

在这两种情况下,密钥都有一个用于在外部查询中进行排序的列。