将 sql 中 table 上的字符串替换为不同的字符串

Replacing a string with a different string on a table in sql

大家下午好。

我正在尝试替换 sql 中特定列中的查询结果。 table 如下:

+-----------+----------+-------+-------+---------+
| firstName | lastName | major | minor | credits |
+-----------+----------+-------+-------+---------+
| Owen      | McCarthy | Math  | CSCI  |       0 |
| Mary      | Jones    | Math  | CSCI  |      42 |
+-----------+----------+-------+-------+---------+

我需要将 Math 改为 Mathematics,将 CSCI 改为 Computer Science。有没有我可以替换的特定代码?

我用来生成这个 table 的代码是这样的:

select firstName, lastname, major, minor, credits from student where major = 'Math' and minor = 'CSCI'; 

感谢任何帮助,谢谢,祝你周日愉快

执行此操作的最佳方法是使用联接进行查找 table。这样,您可以确保所有替换都使用相同的值。

不过,在单个查询中,您可以使用 case 表达式。但是,在您的查询中,由于 where 子句,这甚至不是必需的。只需使用常量:

select firstName, lastname,
       'Mathematics' as major, 'Computer Science' as minor, credits
from student
where major = 'Math' and minor = 'CSCI'; 

如果没有 where 子句,您会这样做:

select firstName, lastname,
       (case when major = 'Math' then 'Mathematics' else major end) as major,
       (case when minor = 'CSCI' then 'Computer Science' else minor end) as minor,
       credits
from student;

您可以将其更改为

select 
    firstName, 
    lastname, 
    CASE WHEN major="Math" THEN "Mathematics"
    ELSE major
    END as 'major',
    CASE WHEN minor="CSCI" THEN "Computer Science"
    ELSE minor
    END as 'minor',
    credits 
from student 
where major = 'Math' 
and minor = 'CSCI'
;

纯粹在 select 的 case-by-case 基础上处理它们,但听起来你最好通过 [=11] 更改学生 table 中的定义=](对于 CSCI 也是如此)如果你可以的话。