mysql - SQL 简单案例语句

标签 mysql sql case

这个简单的 SQL 语句似乎返回了错误的答案。有人可以告诉我哪里出错了。我正在使用 MySQL Workbench。

我使用以下命令创建并填充表:

drop table if exists TRIANGLES;
create table TRIANGLES(A int, B int, C int);
insert into TRIANGLES values(20,20,23);
insert into TRIANGLES values(20,20,20);
insert into TRIANGLES values(20,21,22);
insert into TRIANGLES values(13,14,30);

然后我将我的三角形类型查询执行为:

select (case
when A+B<=C then 'Not a Triangle'
when B+C<=A then 'Not a Triangle'
when A+C<=B then 'Not a Triangle'
when A=B=C then 'Equilateral'
when A=B and B!=C then 'Isoscelus'
when B=C and C!=A then 'Isoscelus'
when A=C and B!=C then 'Isoscelus'
when A!=B!=C then 'Scalene'
end) as typ from TRIANGLES;

但我得到的答案是:

Isoscelus
Scalene -- bad result
Scalene
Not a Triangle

谢谢。

最佳答案

使用 A=B 和 B=C 代替 A=B=C:

select *, (case
when A+B<=C then 'Not a Triangle'
when B+C<=A then 'Not a Triangle'
when A+C<=B then 'Not a Triangle'
when A=B and b=C then 'Equilateral'
when A=B and B!=C then 'Isoscelus'
when B=C and C!=A then 'Isoscelus'
when A=C and B!=C then 'Isoscelus'
when A!=B and B!=C and A!=C then 'Scalene' -- or just use: ELSE 'Scalene'
end) as typ 
from TRIANGLES;

结果:

A            B            C            typ             
-------------------------------------------------------
20           20           23           Isoscelus       
20           20           20           Equilateral     
20           21           22           Scalene         
13           14           30           Not a Triangle  

关于mysql - SQL 简单案例语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240819/

相关文章:

python - MySQL 更新语句不起作用

mysql - INSERT INTO SELECT 如何返回一组插入 ID

java - 我如何知道我的数据库中触发了多少个查询?

mysql - 与空集比较

mysql - 如何 JOIN 两个表,然后使用 CASE 表达式来确定它们的 ORDER BY 方式? SQL

mysql - 高效的 CASE 语句,SQL

mysql - ER_BAD_FIELD_ERROR : Unknown column 'table.column' in 'on clause'

php - 无法从数据库在 joomla 中创建 super 用户

sql - exec 失败,因为名称不是有效的标识符?

SQL Server : difference in days for two dates in separate rows