mysql:内部查询在 selectif 语句中不起作用

Posted

技术标签:

【中文标题】mysql:内部查询在 selectif 语句中不起作用【英文标题】:mysql: inner query is not working inside selectif statement 【发布时间】:2016-03-30 22:04:38 【问题描述】:

如果电子邮件被列入黑名单,我希望以下查询的结果为 Y,否则运行内部查询并返回特定的设施名称。

Select if (EmailBlacklisted = 'Y', 'Y', 
     'select a.facilityname from facility a
     inner join domainfacility b on a.facility_ID=b.facility_facility_ID
      inner join domain c on b.domain_Domain_ID = c.Domain_ID 
     where a.facilitystatus="A" and c.DomainName = "cd.com" ') 
from domain where DomainName= 'cd.com';

如果 emailBlacklisted 在域表中为 N,则查询返回与 RESULT 相同的内部查询。请帮忙

【问题讨论】:

编辑您的问题并提供示例数据和所需结果。 【参考方案1】:

通常,您只需返回设施名称即可解决此问题:

select f.facilityname
from facility f inner join
     domainfacility df
     on a.facility_ID = b.facility_facility_ID inner join
     domain d
     on df.domain_Domain_ID = d.Domain_ID 
     where f.facilitystatus = 'A' and d.DomainName = 'cd.com'
where d.DomainName = 'cd.com' and d.EmailBlacklisted <> 'Y';

然后,如果这不返回任何内容,则表明被列入黑名单。对于这样的名称,您可以只返回 Y

select (case when d.EmailBlacklisted = 'Y' then 'Y' else f.facilityname end)
from facility f inner join
     domainfacility df
     on a.facility_ID = b.facility_facility_ID inner join
     domain d
     on df.domain_Domain_ID = d.Domain_ID 
     where f.facilitystatus = 'A' and d.DomainName = 'cd.com'
where d.DomainName = 'cd.com';

但这似乎是一种将名称与标志混合在一起的奇怪混淆。

【讨论】:

【参考方案2】:

试试这个:

SELECT IF(d.EmailBlacklisted = 'Y', 'Y', a.facilityname)
FROM domain d
LEFT OUTER JOIN domainfacility b ON b.domain_Domain_ID = d.Domain_ID 
LEFT OUTER JOIN facility a ON b.facility_facility_ID = a.facility_ID AND a.facilitystatus = 'A'
WHERE d.DomainName= 'cd.com';

【讨论】:

以上是关于mysql:内部查询在 selectif 语句中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

PHP - 为 mysql 生成动态 IF 语句

MySQL查询语句的不等于怎么写

sql语句中if条件的使用

SQL语句中模糊查询中不区分大小写怎么写?如:select × from table where number like‘%PK%’

mysql 多表联合查询语句怎么写

怎么优化mysql查询语句