2017-08-08 99 views
1

我在做什么错了?如果有更多的人单身而不是结婚,并且没有反之,则需要显示“是”。我只是希望它只显示yes或no。带有打印的SQL IF语句

IF 
select COUNT(StudMaritalStatus) from students WHERE StudMaritalStatus = "M" 
< 
select COUNT(StudMaritalStatus) from students WHERE StudMaritalStatus = "S" 
Print 'Yes' 
ELSE 
Print 'No'; 
+0

https://stackoverflow.com/questions/8147834/how-to-echo-print-statements-while-executing-a-sql-script –

+0

为了澄清我得到的错误说我正在使用错误的IF语句syntacs。 –

+0

请发布语法错误语句。 –

回答

2

以及考虑到MySQL使用:

IF expression THEN 
     expression   
    ELSE 
ENDIF; 

你是不是用select语句

DECLARE married int, single int 

SET married = select COUNT(StudMaritalStatus) from students WHERE StudMaritalStatus = 'M' 

SET single = select COUNT(StudMaritalStatus) from students WHERE StudMaritalStatus = 'S' 

IF married < single THEN 
    PRINT 'YES' 
ELSE 
    PRINT 'NO' 
END IF 

在回答对你的语法错了做得更好 https://dev.mysql.com/doc/refman/5.7/en/if.html

+0

not the最优雅的解决方案,但它显示了他的语法错误以及如何纠正它。 @丹你的解决方案优化,以最大限度地减少数据库调用..首先简单到复杂:) – mvermef

+0

这没有奏效。 –

2

你想要的东西是这样的:

select case when married >= single then 'M' else 'S' end 
from 
(
select sum(case when StudMaritalStatus = 'M' then 1 else 0 end) married 
, sum (case when StudMaritalStatus = 'S' then 1 else 0 end) single 
from students 
) derivedTable 

打破关系取决于您的业务需求,我们都不知道。