英文:
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:
SQL query:
Output:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论