有关union和concat的SQL查询

时间:2018-11-07 06:56:31

标签: mysql sql sql-server

我需要从两个表中选择并集值,还需要在结果值中添加前缀。 例如:-

select concat('Source-',id), concat('Source-',name)
from src_tbl where id IS not NULL and name IS not NULL    
UNION
select concat('Destination-',id), concat('Destination-',name)
from dstn_table where id IS not NULL and name IS not NULL  
order by name

Union和concat分别工作,但是我正在合并它不起作用,并抛出错误“在联合体两边的表中找不到该名称”。该列虽然存在

3 个答案:

答案 0 :(得分:1)

在第一张表的列名中使用别名

  select concat('Source-',id) source_id,
         concat('Source-',name) name
         from src_tbl where id IS not NULL and name IS not NULL    
         UNION
  select concat('Destination-',id),
         concat('Destination-',name)
         from dstn_table where id IS not NULL and name IS not NULL  
         order by name

答案 1 :(得分:0)

您需要为列名定义别名

select concat('Source-',id) as id, concat('Source-',name) as name from src_tbl where id IS not NULL and name IS not NULL    
UNION
select concat('Destination-',id), concat('Destination-',name) from dstn_table where id IS not NULL and name IS not NULL order by name

答案 2 :(得分:0)

order by子句引用两个查询的结果。在此处添加别名,您应该会很好:

SELECT CONCAT('Source-',id), CONCAT('Source-', name) AS name
FROM   src_tbl
WHERE  id IS NOT NULL AND name IS NOT NULL    
UNION
SELECT CONCAT('Destination-',id), CONCAT('Destination-',name) AS name
FROM   dstn_table
WHERE  id IS NOT NULL AND name IS NOT NULL  
ORDER BY name