2017-08-08 120 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 

打破關係取決於您的業務需求,我們都不知道。