无法在只读SQL中的字段之前添加字符串

时间:2018-05-06 01:18:52

标签: sql

故障

在Reason中包含的字段之前将“类型”和“代码”添加到只读数据库。

原始问题

此处需要使用Union运算符。需要找到某个信用码和工作类型,请参阅下面的错误代码。

我的代码:

SELECT cust_id, creditcode as 'Reason'
FROM publishers
WHERE creditcode IS 'D'
UNION 
SELECT cust_id, jobtype as 'Reason'
FROM bookjobs
WHERE jobtype IS 'R';

给出:

cust_id     Reason
----------  ----------
A01         R
D04         D
E05         R

但是,需要的是:

cust_id     Reason
----------  ----------
A01         Type R
D04         Code D
E05         Type R

2 个答案:

答案 0 :(得分:2)

如果您使用PostgreSQL,则可以按照以下方式执行此操作,其中||执行字符串连接。我也添加了ORDER BY子句进行排序。

SELECT
    cust_id, 
    'Code ' || creditcode as 'Reason'
FROM publishers
WHERE creditcode = 'D'

UNION ALL

SELECT 
    cust_id, 
    'Type ' || jobtype as 'Reason'
FROM bookjobs
WHERE jobtype = 'R'

ORDER BY cust_id;

对于mysql,您可以使用CONCAT()功能:

SELECT
    cust_id, 
    CONCAT('Code ' , creditcode) as 'Reason'

FROM publishers
WHERE creditcode = 'D'

UNION ALL

SELECT 
    cust_id,
    CONCAT('Type ' , jobtype) as 'Reason'

FROM bookjobs
WHERE jobtype = 'R'

ORDER BY cust_id;

答案 1 :(得分:1)

你可能想要这样的东西:

SELECT cust_id, 'CODE ' || creditcode as Reason
FROM publishers
WHERE creditcode = 'D'
UNION ALL
SELECT cust_id, 'TYPE ' || jobtype as Reason
FROM bookjobs
WHERE jobtype = 'R';

注意:

  • ||是ANSI标准字符串连接运算符。某些数据库有其他方法,例如CONCAT()+
  • 使用UNION ALL而不是UNION - 除非您特别希望产生删除重复项的开销。
  • =是比较SQL中值的传统方式,而不是IS
  • 不要在单引号中包含列别名。仅对字符串和日期常量使用单引号。