我想检查条件内的查询
如果查询为空,我想要值'NO',如果查询不为空,我想要值'YES'
通过尝试,如果条件出现错误。
我的查询是
SELECT Count(SiteID)
from ChartFace
Inner Join Structure on Structure.StructureID = ChartFace.StructureID
where (ContractNumber='C197960' AND LineNumber=4)
AND (ISNULL('MN420628', '-1')='-1' or SiteID = 'MN420628')
我尝试了
IF(above query is NULL) THEN 'NO'
ELSE 'YES'
END IF
稍后我需要在select语句中
Select ContractID, ContractName, IF(above query is NULL) THEN 'NO'
ELSE 'YES' AS Status FROM Contract
我该怎么做?
答案 0 :(得分:0)
在 mysql 中,您可以使用 exist
喜欢
SELECT ContractID, ContractName,IF( EXISTS(
SELECT
Count(SiteID)
FROM ChartFace
INNER JOIN Structure ON Structure.StructureID = ChartFace.StructureID
WHERE (ContractNumber='C197960' AND LineNumber=4) AND
(ISNULL('MN420628', '-1')='-1' or SiteID = 'MN420628')),'yes','No') Status
FROM Contract ;
在 SQL Server 中,类似
SELECT ContractID, ContractName,CASE
WHEN EXISTS (SELECT
Count(SiteID)
FROM ChartFace
INNER JOIN Structure ON Structure.StructureID = ChartFace.StructureID
WHERE (ContractNumber='C197960' AND LineNumber=4) AND
(ISNULL('MN420628', '-1')='-1' or SiteID = 'MN420628')) THEN 'yes'
ELSE 'NO'
END as Status
FROM Contract ;
答案 1 :(得分:0)
Select ContractID, ContractName, case when SiteCount > 0 then 'YES' ELSE 'NO' END as Status
FROM Contract c
left join (
SELECT ContractNumber, Count(SiteID) as SiteCount
from ChartFace
Inner Join Structure on Structure.StructureID = ChartFace.StructureID
where (ContractNumber='C197960' AND LineNumber=4)
AND (ISNULL('MN420628', '-1')='-1' or SiteID = 'MN420628')
group by ContractNumber
) tbl on c.ContractNumber = tbl.ContractNumber
答案 2 :(得分:0)
我相信CASE是您的追求。
SELECT ContractID, ContractName,
CASE
WHEN COUNT(SiteID) IS 0 THEN 'NO'
ELSE 'YES'
END AS HasSite
FROM ChartFace
INNER JOIN Structure on Structure.StructureID = ChartFace.StructureID
WHERE ContractNumber='C197960' AND LineNumber=4
AND (ISNULL('MN420628', '-1')='-1' or SiteID = 'MN420628')
这将返回以下内容:
{ ContractID: 3, ContractName: 'REALLY IMPORTANT CONTRACT', HasSite: 'NO' }
答案 3 :(得分:0)
COUNT(*)
永远不能为null。您可以将其与零进行比较:
select
contractid,
contractname,
case when
(
select count(*)
from chartface cf
join structure s on s.structureid = cf.structureid
where cf.contractnumber = c.contractid
and ...
) = 0 then 'NO' else 'YES' end as status
from contract c
order by contractid;
但是,如果您只想检查是否存在,为什么要数一数呢?为此,我们在SQL中使用EXISTS
或IN
:
select
contractid,
contractname,
case when contractid in
(
select cf.contractnumber
from chartface cf
join structure s on s.structureid = cf.structureid
where ...
) then 'YES' else 'NO' end as status
from contract
order by contractid;