简体   繁体   English

关于 union 和 concat 的 SQL 查询

[英]SQL query about union and concat

I need to select union values from two table and also add prefix to the result values.我需要从两个表中选择联合值,并为结果值添加前缀。 Eg:-例如:-

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 and concat is working separately but wen I am combining it's not working and throwing error "that name is not found from tables on both sides of union". Union 和 concat 是分开工作的,但我结合它不起作用并抛出错误“从联合双方的表中找不到该名称”。 The column is present though该列虽然存在

use alias in 1st table column name在第一个表列名中使用别名

  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

you need to define alias for column name您需要为列名定义别名

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

The order by clause refers to the result of both queries. order by子句引用两个查询的结果。 Add aliases there and you should be good to go:在那里添加别名,你应该很高兴:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM