Case语句为什么返回不满足条件的记录?

huangapple go评论70阅读模式
英文:

Why case statement returning records whose condition does not met?

问题

我正在尝试从数据库中仅获取与CASE语句中匹配的ID相符的单个记录。

学生表数据:

SQL查询:

输出:

查询有什么问题?

我尝试获取与匹配的ID相关的单个记录,但它返回了所有记录。

英文:

I am trying to fetch only single record from database for whose id is met in case statement

Student table data:

Case语句为什么返回不满足条件的记录?

SQL query:

Case语句为什么返回不满足条件的记录?

Output:

Case语句为什么返回不满足条件的记录?

What is wrong with the query?

I tried to get a single record specific to the matching id but it is returning all the records

答案1

得分: 1

如果您只想提取id = 5的记录,那么您需要使用WHERE子句来筛选记录。
CASE语句只是一个条件语句,不会过滤输出。
如果您想使用相同的查询,请尝试以下查询:

SELECT id, name,
CASE WHEN id = 5 THEN "Found" END FROM student WHERE id = 5;

因为我们已经添加了WHERE子句来筛选id = 5的记录,所以不需要CASE语句,您可以直接在最后一列硬编码"Found"。
如果我们的输出在id列中有多种类型,并且如果您需要在最后一列中填充多个状态,则可以使用CASE语句,否则在查询执行中会浪费时间。

请尝试以下查询:

SELECT id, name, "Found" FROM student WHERE id = 5;

英文:

If you want to fetch only id = 5 records then you have to use the WHERE clause which will filter the records.
CASE statement is just a conditional statement it won't filter output.
If you want to use your same query then try below

SELECT id, name,
CASE id =5 THEN "Found" END FROM student WHERE id =5;

As we already added WHERE clause which will filter id = 5 record, we no need CASE statement you can directly hard code "Found" in the last column.
If our output have multiple types in the id column and if you need to populate more that one status in the last column then you can go for CASE statement, unless it's waste of time in the query execution

Try below

SELECT id, name,"Found" FROM student WHERE id =5;

huangapple
  • 本文由 发表于 2023年6月1日 12:10:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定